android studio listview控件基础

public class MainActivityFragment extends Fragment {
    private static final String[] str=new String[]{"rain","sunshine"};
    private ListView listView;
    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootview=inflater.inflate(R.layout.fragment_main, container, false);
        listView=(ListView)rootview.findViewById(R.id.list_item);
        ArrayAdapter arrayAdapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,str);
        listView.setAdapter(arrayAdapter);
        return rootview;
    }
}

自定义列表显示:

新建一个customlistlayout,其中放置一个texview控件,进行相关设置,id为text;

mainactivity中代码如下:

public class MainActivity extends AppCompatActivity {
    String[] strings=new String[]{"india","china"};
    ListView listView;
    ArrayAdapter arrayAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.listView);
        arrayAdapter=new ArrayAdapter(this,R.layout.customlistview,R.id.text,strings);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(),adapterView.getItemAtPosition(i)+"",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

设置onselect和onpress的颜色:

第一步:

在color.xml中加入:

<color name="select">#c8fd17color>
<color name="press">#0cc6fecolor>
第二步:

在drawable文件夹下新建一个xml文件:

xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@color/press">item>
    <item
        android:state_selected="true"
        android:drawable="@color/select">item>
selector>
第三步:

在mainactivity中的onitemclick里面加入:

view.setSelected(true);
现在就ok了!


你可能感兴趣的:(android studio listview控件基础)