Android无法突出显示listview中的项目

时间:2014-02-26 18:29:46

标签: android listview android-listview

我正在尝试突出显示listview中的项目,因此当用户点击listview中的项目时,会启动新活动并突出显示listview中的特定项目。

我知道这可以用片段完成,但我更喜欢活动,因为它使我的工作更容易。

所以这是自定义适配器

public class CustomAdapter extends BaseAdapter{

    Context mycontext;
    ArrayList<String> contactsList;
    LayoutInflater minflater;

    public CustomAdapter(Context context, ArrayList<String> list)
    {
        this.mycontext=context;
        contactsList=list;
        minflater =LayoutInflater.from(context);

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


    @Override
    public Object getItem(int position)
    {
        return contactsList.get(position);
    }


    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }


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

        if (convertView !=null)
        {
            LayoutInflater inflater=(LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v =inflater.inflate(R.layout.item_layout,null);

            TextView tv=(TextView)v.findViewById(R.id.itemName);

            if (position ==1)
            {
                convertView.setBackgroundColor(Color.BLUE);

            }
        }
        return  convertView;
    }
}

这是我的item_layout.xml

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

    <TextView
        android:id="@+id/itemName"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true" />


</RelativeLayout>

这是被抛出的例外 -

  1559-1559/com.example.listviewandroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.listviewandroid, PID: 1559
    java.lang.NullPointerException
            at android.widget.AbsListView.obtainView(AbsListView.java:2265)
            at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
            at android.widget.ListView.onMeasure(ListView.java:1175)
            at android.view.View.measure(View.java:16458)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16458)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
            at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1052)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
            at android.view.View.measure(View.java:16458)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16458)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
            at android.view.View.measure(View.java:16458)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2289)
            at android.view.View.measure(View.java:16458)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1914)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1111)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1293)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5582)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
            at android.view.Choreographer.doCallbacks(Choreographer.java:562)
            at android.view.Choreographer.doFrame(Choreographer.java:532)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4998)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
            at dalvik.system.NativeStart.main(Native Method)

如果listview位置索引是1,我试图给item_lauout充气并用蓝色突出显示textview。我在这里做错了什么。

编辑2:

 1810-1810/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.listviewandroid, PID: 1810
    java.lang.NullPointerException
            at android.widget.AbsListView.obtainView(AbsListView.java:2265)
            at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
            at android.widget.ListView.onMeasure(ListView.java:1175)
            at android.view.View.measure(View.java:16497)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16497)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
            at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1052)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
            at android.view.View.measure(View.java:16497)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16497)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
            at android.view.View.measure(View.java:16497)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
            at android.view.View.measure(View.java:16497)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
            at android.view.Choreographer.doCallbacks(Choreographer.java:574)
            at android.view.Choreographer.doFrame(Choreographer.java:544)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

编辑3:主要活动代码

package com.example.listviewandroid;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import android.text.format.Time;
import java.util.Date;

public class MainActivity extends Activity {
    ListView listView ;
    static final  String STE = "";
    static final String STM = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState !=null)
        {
            restoreState(savedInstanceState);
        }
        listView = (ListView) findViewById(R.id.listView);

        TextView textviewmenu= (TextView) findViewById(R.id.textViewMenu);
        textviewmenu.setBackgroundColor(Color.rgb(89,89,89));
        textviewmenu.setTextColor(Color.WHITE);

        String[] values = getResources().getStringArray(R.array.menuList);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);


        // Assign adapter to ListView
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);


                // Show Alert

                switch( position )
                {

                    case 1:  Intent newActivity = new Intent(MainActivity.this,Activity2.class);
                        startActivity(newActivity);
                        break;

                    case 2:  Intent newActivity1 = new Intent(MainActivity.this,Activity3.class);
                        startActivity(newActivity1);
                        break;
                    case 3:  Intent newActivity2 = new Intent(MainActivity.this,Activity4.class);
                        startActivity(newActivity2);
                        break;
                    case 4:  Intent newActivity3 = new Intent(MainActivity.this,Activity5.class);
                        startActivity(newActivity3);
                        break;
                    case 5:  Intent newActivity4 = new Intent(MainActivity.this,Activity6.class);
                        startActivity(newActivity4);
                        break;

                }
                Toast.makeText(getApplicationContext(),
                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                        .show();

            }

        });
        Time now = new Time();
        now.setToNow();
        if (savedInstanceState ==null )
        {
        TextView textview2= (TextView)findViewById(R.id.MAtextView2);
        textview2.setText(now.hour+" : "+now.minute);
        }


    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);


        TextView startimetext= (TextView) findViewById(R.id.MAtextView2);
        outState.putString(STE,startimetext.getText().toString());



        TextView endtimetext= (TextView) findViewById(R.id.MAtextView3);
        outState.putString(STM,startimetext.getText().toString());


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void SetEndTime(View view) {
        Time now = new Time();
        now.setToNow();
        TextView textview3= (TextView)findViewById(R.id.MAtextView3);
        textview3.setText(now.hour+" : "+now.minute);

    }

    public void NextActivity(View view) {
        Intent myIntent = new Intent(MainActivity.this,Activity2.class);
       MainActivity.this.startActivity(myIntent);
        this.overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);

    }

    private void restoreState(Bundle savedInstanceState) {
        TextView startimetext= (TextView) findViewById(R.id.MAtextView2);

        TextView endtimetext= (TextView) findViewById(R.id.MAtextView3);


      startimetext.setText(savedInstanceState.getString(STE));
      endtimetext.setText(savedInstanceState.getString(STM));



    }
}

3 个答案:

答案 0 :(得分:1)

在你的getView()中:

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

    if (convertView == null) {

                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_layout, null);
            } 
                TextView tv=(TextView)convertView .findViewById(R.id.itemName);

                 try {

            if(position ==1){

                convertView.setBackgroundColor(Color.GREEN);
            }


        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


return  convertView;

}

保持选中项目:

首先:在适配器中定义这些东西:

private int selectedIndex;
    private int selectedColor = Color.parseColor("#1b1b1b");


In your adapter class; add this method:

public void setSelectedIndex(int position)
    {
        selectedIndex = position;
        notifyDataSetChanged();
    }

在你的getView()中,添加这些行。

if(selectedIndex!= -1 && position == selectedIndex)
        {
            txtTitle.setBackgroundColor(Color.BLACK);
        }
        else
        {
            txtTitle.setBackgroundColor(selectedColor);
        }

现在应该工作.. :))

答案 1 :(得分:0)

  1. if (convertView !=null)更改为if (convertView ==null)您 当您无法重复使用时,需要对布局进行充气。
  2. 您需要在列表视图中添加单击侦听器以突出显示特定的行/列表项。以下是添加点击监听器的方法。更新视图以突出显示它。

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Intent intent = new Intent(MainActivity.this, SendMessage.class);
            String message = "abc";
            intent.putExtra(EXTRA_MESSAGE, message);
            startActivity(intent);
        }
    });
    
  3. 您正在变量v中设置膨胀视图并返回convertView。请将v指定给convertView或返回v。

答案 2 :(得分:0)

我认为你不能在匿名类中使用 listView 。您必须使用 AdapterView arg0

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view,
                int position, long id) {
            AnyObject obj=(AnyObject)arg0.getItemAtPosition(position);

                            ........
                            .........
                            .........

        }
    });