通过按钮编辑listView内的TextView文本

时间:2012-08-09 17:26:49

标签: android android-listview android-arrayadapter

我有ListView.I也有按钮。它们位于RelativeLayout内。我希望能够通过onClick(View v)按钮更改所选ListView项目的TexView文本。 ListView布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="22px"
        android:layout_height="22px"
        android:layout_marginLeft="4px"
        android:layout_marginRight="10px"
        android:layout_marginTop="4px"
        android:src="@drawable/ic_launcher" >
    </ImageView>

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textSize="20px" >
    </TextView>

</LinearLayout>

主要活动:

public class MainActivity extends Activity {
    private TextView mTextView;
    private ListView my_list;
    private MyArrayAdapter adapt;
    Button mybutton;

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle); 

        String[] mContacts = {
                "Jacob Anderson dsfd sdfdf sdfsd sdfds", "Emily Duncan", "Michael Fuller", 
                "Emma Greenman", "Joshua Harrison", "Madison Johnson",
                "Matthew Cotman", "Olivia Lawson", "Andrew Chapman", 
                "Daniel Honeyman", "Isabella Jackson", "William Patterson", 
                "Joseph Godwin", "Samantha Bush", "Christopher Gatema55"};

        setContentView(R.layout.activity_main);
        my_list=(ListView)findViewById(R.id.listView1);
        adapt=new MyArrayAdapter(this, mContacts, 0);
        my_list.setAdapter(adapt);

        mybutton = (Button)findViewById(R.id.button1);
        mybutton.setOnClickListener(new OnClickListener() {     
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

如果我想像这样编辑TextView,我该怎么办:

        SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);
    TextViewOfSelectedItem.setText(text, BufferType.SPANNABLE);

如何通过项目位置获取ListView项目的TextViewOfSelectedItem或TextView?

1 个答案:

答案 0 :(得分:0)

您可以使用setOnItemClickListener()获取所选项目的文字。你可以用这种方式。

    my_list.setOnItemClickListener(new OnItemClickListener() {

  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
 long arg3) {
         // TODO Auto-generated method stub
    String  getSelectedTextOfList = yourList.get(pos); // here you can get selected item.
 }
});