Android GridView/ListView点击事件并改变控件的背景颜色//记录解决parent.getChildAt()空指针问题 (笔记)

主要记录:1.解决parent.getChildAt()空指针的问题

 int firstVisiblePosition=parent.getFirstVisiblePosition();//获取当前可视列表的第一个View的地址
 int i;//i为视图中目标item的地址
int item=i-firstVisiblePosition;//例如:firstVisiblePosition==10;i==12;那么item==2,就是说你想要的View是可视列表中的第二个
View v=parent.getChildAt(item);//获取到当前目标的View

2.动态改变控件的背景颜色:setBackgroundColor(Color.parseColor());//详细代码请往下看

针对以上,做了一个简单的Demo(附代码):

GridView展示Demo,布局及功能如下:
(如果左边是一列的信息可以用ListView,这里我用了GridView是为了下一个Demo做铺垫)
1)左边为GiridView,主干标题栏
2)右边对应左边标题栏的详细信息,设置了两个TextView进行展示
3)点击左边GridView的item,该item的背景颜色会改变,右边对应更新相关信息。

效果图如下:

Android GridView/ListView点击事件并改变控件的背景颜色//记录解决parent.getChildAt()空指针问题 (笔记)_第1张图片

1)配置布局
1.首先配置主界面的xml:将主页控件的布局改为水平布置:orientation=“horizontal”

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.suyingxin.myapplication.MainActivity">

    <GridView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/grid_vs"
        android:numColumns="1"
        android:horizontalSpacing="24dp"
        android:verticalSpacing="24dp"
        android:scrollbars="none"
        android:transcriptMode="alwaysScroll"
        android:stretchMode="columnWidth">
    </GridView>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="200dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:alpha="0.6" />

        <TextView
            android:id="@+id/tv_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp"/>

    </LinearLayout>
    
</LinearLayout>


2.配置GridView的item布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/layout_gv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:orientation="vertical"
        android:background="@color/myColor">
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textSize="24sp"
            />

        <ImageView
            android:id="@+id/image_view"
            android:layout_marginTop="6dp"
            android:layout_gravity="center"
            android:layout_width="60dp"
            android:layout_height="60dp"
            />

    </LinearLayout>

</LinearLayout>

2)配置Bean数据(这个就不附代码了,加上get、set方法就好了)
1.新建一个左边数据的Bean:命名为GridViewBean,两个变量:标题名name和图片的来源 resourceId;

2.新建一个右边数据的Bean:命名为contentBean,两个变量:title和text;

3)MainActivity:主要就是三个步骤 1.加载布局的id 2.初始化数据 3.加载自定义适配器的布局

public class MainActivity extends AppCompatActivity {
     

    GridView girdView;

    GridAdapter adapter1;

    TextView title;
    TextView text;

    LinearLayout gv_ll;

    List<GridViewBean> gridList=new ArrayList<>();

    List<contentBean> listBean=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        girdView= (GridView) findViewById(R.id.grid_vs);
        title= (TextView) findViewById(R.id.tv_title);
        text= (TextView) findViewById(R.id.tv_text);
        gv_ll= (LinearLayout) findViewById(R.id.layout_gv);


        initData();

        Log.e("MainActivity=====","girdView"+gridList.size());
        Log.e("MainActivity=====","lv_List"+listBean.size());

        setLeftAdapter();

        girdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     

                //改变当前点击item的背景颜色
                int firstVisiblePosition=parent.getFirstVisiblePosition();//获取当前GridView在屏幕中可见的第一个item
                int lastVisiblePosition=parent.getLastVisiblePosition();//获取当前GridView在屏幕中可见的最后一个item

                for (int i=firstVisiblePosition;i<lastVisiblePosition+1;i++){
     
                    int item=i-firstVisiblePosition;
                    if (item<0||item>parent.getChildCount()){
     
                        Log.d("MainActivity------","SelectionItem---Error");
                    }else {
     
                        View v=parent.getChildAt(item);//如果当前的子类不在视图列表内,parent.getChildAt()就会报空指针的错误,所以item要处理一下
                        if (i==position){
     
                            view.findViewById(R.id.layout_gv).setBackgroundColor(Color.parseColor("#3F51B5"));
                        }else {
     
                            v.findViewById(R.id.layout_gv).setBackgroundColor(Color.parseColor("#D1EEEE"));
                        }
                    }
                }

                setRightView(position);

            }
        });

    }

   //初始化GridView的Adapter
    private void setLeftAdapter() {
     
        adapter1=new GridAdapter(MainActivity.this,gridList);
        girdView.setAdapter(adapter1);

    }
    
    //初始化数据
    private void initData() {
     
        //初始化左边GridView数据
        for (int i=0;i<10;i++){
     
            GridViewBean gridView=new GridViewBean("水果"+i,R.drawable.fruit);
            gridList.add(gridView);

        }

        //初始化右边ListView数据
        List<String> listTitle=new ArrayList<>();

        listTitle.add("苹果");
        listTitle.add("香蕉");
        listTitle.add("芒果");
        listTitle.add("雪梨");
        listTitle.add("草莓");
        listTitle.add("蓝莓");
        listTitle.add("西瓜");
        listTitle.add("哈密瓜");
        listTitle.add("樱桃");
        listTitle.add("橙子");

        List<String> listText=new ArrayList<>();

        for (int i=0;i<10;i++){
     
            listText.add(listTitle.get(i)+i);
        }

        for (int i=0;i<listText.size();i++){
     
            String title=listTitle.get(i);
            String text=listText.get(i);
            contentBean listBean1=new contentBean(title,text);
            listBean.add(listBean1);
        }

    }

    private void setRightView(int position){
     
        title.setText(listBean.get(position).getTitle());
        text.setText(listBean.get(position).getText());

    }

}

4)自定义适配器

public class GridAdapter extends BaseAdapter {
     

    Context context;
    int position;
    List<GridViewBean> list;

    public GridAdapter(Context context,List<GridViewBean> list ){
     
        super();

        this.context=context;
        this.list=list;

    }

    @Override
    public int getCount() {
     
        return  list.size();

    }

    @Override
    public Object getItem(int position) {
     

        return list.get(position);

    }

    @Override
    public long getItemId(int position) {
     

        return position;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
     

        View view;
        ViewHolder viewHolder;

        if (convertView==null){
     
            view= LayoutInflater.from(context).inflate(R.layout.item_gridview_adapter,null);
            viewHolder=new ViewHolder();
            viewHolder.textView=view.findViewById(R.id.tv_name);
            viewHolder.imageView=view.findViewById(R.id.image_view);

            view.setTag(viewHolder);

        }else {
     
            view=convertView;
            viewHolder= (ViewHolder) view.getTag();
        }

        viewHolder.textView.setText(list.get(position).getName());
        viewHolder.imageView.setImageResource(list.get(position).getResourceId());

        return view;


    }

    class ViewHolder{
     
        TextView textView;
        ImageView imageView;
    }


}

你可能感兴趣的:(android,listview,gridview)