android - ListView 项目/按钮android的actionlistener

标签 android database button actionlistener

package com.xpresso;

//import android.R;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
//import com.xpresso.SQLiteAdapter;

public class Xpresso extends Activity implements TextToSpeech.OnInitListener,OnClickListener {

    Button left, right, rg_left, rg_right, lf_left, lf_right,hello,how,goodbye,thankyou,okay,goodmorning,letsgo,goodnight;
    Button maintalkbutton,lefttalkbutton,righttalkbutton;
    private TextToSpeech mTts;

    ViewFlipper flipper;
    EditText main_text,lefttext,righttext;
    private SQLiteAdapter mySQLiteAdapter;
    ListView listContent;
    SimpleCursorAdapter cursorAdapter;
    Cursor cursor;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        mTts = new TextToSpeech(this,this);
        final Animation b = AnimationUtils.loadAnimation(this, R.anim.fade);


        hello = (Button) findViewById(R.id.hello);
        how = (Button) findViewById(R.id.how);
        goodbye = (Button) findViewById(R.id.goodbye);
        okay = (Button) findViewById(R.id.okay);
        thankyou = (Button) findViewById(R.id.thankyou);
        goodmorning = (Button) findViewById(R.id.goodmorning);
        letsgo = (Button) findViewById(R.id.letsgo);
        goodnight = (Button) findViewById(R.id.goodnight);



        hello.setOnClickListener(this);
        how.setOnClickListener(this);
        goodbye.setOnClickListener(this);
        okay.setOnClickListener(this);
        thankyou.setOnClickListener(this);
        goodmorning.setOnClickListener(this);
        letsgo.setOnClickListener(this);
        goodnight.setOnClickListener(this);


        main_text = (EditText)findViewById(R.id.main_text);
        lefttext = (EditText)findViewById(R.id.lefttext);
        righttext = (EditText)findViewById(R.id.righttext);


        left = (Button) findViewById(R.id.left);
        right = (Button) findViewById(R.id.right);

        rg_left = (Button) findViewById(R.id.rg_left);
        rg_right = (Button) findViewById(R.id.rg_right);

        lf_left = (Button) findViewById(R.id.lf_left);
        lf_right = (Button) findViewById(R.id.lf_right);

        maintalkbutton=(Button) findViewById(R.id.maintalkbutton);
        lefttalkbutton=(Button) findViewById(R.id.lefttalkbutton);
        righttalkbutton=(Button) findViewById(R.id.righttalkbutton);



        listContent = (ListView)findViewById(R.id.contentlist);
        flipper = (ViewFlipper) findViewById(R.id.flipper);

        mySQLiteAdapter = new SQLiteAdapter(this);
        mySQLiteAdapter.openToWrite();
        cursor = mySQLiteAdapter.queueAll();
        String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_number, SQLiteAdapter.KEY_phrase};
        int[] to = new int[]{R.id.id, R.id.text1,R.id.text2};
        cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
        listContent.setAdapter(cursorAdapter);
        registerForContextMenu(listContent);

        listContent.setTextFilterEnabled(true);

        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
                {
                flipper.setInAnimation(b);
                flipper.showPrevious(); 

                }
            });

        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
                {
                flipper.setInAnimation(b);
                flipper.showNext(); 

                }
            });

        rg_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
                {
                flipper.setInAnimation(b);
                flipper.showPrevious(); 

                }
            });

        rg_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
                {
                flipper.setInAnimation(b);
                flipper.showNext(); 

                }
            });

        lf_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
                {
                flipper.setInAnimation(b);
                flipper.showPrevious(); 

                }
            });

        lf_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) 
                {
                flipper.setInAnimation(b);
                flipper.showNext(); 

                }
            });



        maintalkbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //String talkit = maintext.getText().toString();
                String maintextstring = main_text.getText().toString();              
                mTts.speak(maintextstring,
                            TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
                            null);

            }
        });

        lefttalkbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //String talkit = maintext.getText().toString();
                String maintextstring = lefttext.getText().toString();               
                mTts.speak(maintextstring,
                            TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
                            null);

            }
        });

        righttalkbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //String talkit = maintext.getText().toString();
                String maintextstring = righttext.getText().toString();              
                mTts.speak(maintextstring,
                            TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
                            null);

            }
        });


    }//end oncreate




        @Override
        protected void onDestroy() 
        {
            super.onDestroy();

            mySQLiteAdapter.close(); //close the sqlite adapter

            if (mTts != null) {
                mTts.stop();
                mTts.shutdown();
            }//shutdown the tts engine

        }

        private void updateList(){
            cursor.requery();
        }

        public boolean onCreateOptionsMenu(Menu menu)
        {
            getMenuInflater().inflate(R.layout.options, menu);
            return true;
        }



      @Override
      public boolean onOptionsItemSelected(MenuItem item)
      {

          switch (item.getItemId()) {

          case R.id.deletealloption:
          {
              mySQLiteAdapter.deleteAll();
              updateList();
              Toast.makeText(this, "Deleted all entries.", Toast.LENGTH_SHORT).show(); 

          }
              case R.id.addoption: 
              {
                  AlertDialog.Builder alert = new AlertDialog.Builder(this);

                  alert.setTitle("Add to phrases");

                  final EditText input = new EditText(this);
                  alert.setView(input);

                  alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    String value = input.getText().toString();
                    mySQLiteAdapter.insert("3", value);

                    updateList();
                    }
                  });

                  alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                      // Canceled.
                    }
                  });

                  alert.show();
              }




          }
          return false;
      } 



      @Override
      public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

        menu.setHeaderTitle("Options");
        menu.add(0, v.getId(), 0, "Delete");
        menu.add(0, v.getId(), 0, "Change");

    }

      @Override
    public boolean onContextItemSelected(MenuItem item) {
          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
          .getMenuInfo();
          int index = info.position;

            if(item.getTitle()=="Delete"){Toast.makeText(this, "Deleted : "+ index+info.id, Toast.LENGTH_SHORT).show(); 
/*function1(item.getItemId());*/}
        else if(item.getTitle()=="Change"){}
        else {return false;}
    return true;
    }


    @Override
    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {
            int result = mTts.setLanguage(Locale.US);
            //mTts.speak("testing testing",TextToSpeech.QUEUE_FLUSH, null);
            if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {
            } else {
                maintalkbutton.setEnabled(true);
            }
        } else {
        }


        }//close oninit




    @Override
    public void onClick(View v) {


        if(v.getId()==R.id.hello)
        {
            mTts.speak("hello",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.how)
        {
            mTts.speak("how?",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.goodbye)
        {
            mTts.speak("Good Bye",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.okay)
        {
            mTts.speak("Okay",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.thankyou)
        {
            mTts.speak("Thank you",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.goodmorning)
        {
            mTts.speak("Good Morning!",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.letsgo)
        {
            mTts.speak("Let's go",TextToSpeech.QUEUE_FLUSH, null);
        }
        if(v.getId()==R.id.goodnight)
        {
            mTts.speak("Good Night",TextToSpeech.QUEUE_FLUSH, null);
        }

    }




}

这是我的主要 Activity 。 这是我的数据库帮助文件 包 com.xpresso;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

        public static final String DATABASE_NAME = "phrasedb";

        public DatabaseHelper(Context context) {
                super(context, DATABASE_NAME, null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
                /*
                 * Create the employee table and populate it with sample data.
                 * In step 6, we will move these hardcoded statements to an XML document.
                 */
                String sql = "CREATE TABLE IF NOT EXISTS insertphrase (" +
                                                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
                                                "phrases TEXT)";
                db.execSQL(sql);


                db.execSQL("INSERT INTO insertphrase (phrases) VALUES ('this is a string')");
                db.execSQL("INSERT INTO insertphrase (phrases) VALUES ('this is a string 2')");


        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROP TABLE IF EXISTS employees");
                onCreate(db);
        }

}

这是我的 sqliteadapter.java

package com.xpresso;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteDatabase.CursorFactory;



public class SQLiteAdapter {



 public static final String MYDATABASE_NAME = "phrasesdatabase_";

 public static final String MYDATABASE_TABLE = "phrasestable";

 public static final int MYDATABASE_VERSION = 1;

 public static final String KEY_ID = "_id";

 public static final String KEY_number = "number";

 public static final String KEY_phrase = "phrase";



 //create table phrasesdatabase (ID integer primary key, Content text not null);

 private static final String SCRIPT_CREATE_DATABASE =

  "create table " + MYDATABASE_TABLE + " ("

  + KEY_ID + " integer primary key autoincrement, "

  + KEY_number + " text not null, "

  + KEY_phrase + " text not null);";



 private SQLiteHelper sqLiteHelper;

 private SQLiteDatabase sqLiteDatabase;



 private Context context;



 public SQLiteAdapter(Context c){

  context = c;

 }



 public SQLiteAdapter openToRead() throws android.database.SQLException {

  sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);

  sqLiteDatabase = sqLiteHelper.getReadableDatabase();

  return this; 

 }



 public SQLiteAdapter openToWrite() throws android.database.SQLException {

  sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);

  sqLiteDatabase = sqLiteHelper.getWritableDatabase();

  return this; 

 }



 public void close(){

  sqLiteHelper.close();

 }



 public long insert(String number, String phrase){



  ContentValues contentValues = new ContentValues();

  contentValues.put(KEY_number, number);

  contentValues.put(KEY_phrase, phrase);

  return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);

 }



 public int deleteAll(){

  return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);

 }



 public Cursor queueAll(){

  String[] columns = new String[]{KEY_ID, KEY_number, KEY_phrase};

  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,

    null, null, null, null, null);



  return cursor;

 }



 public class SQLiteHelper extends SQLiteOpenHelper {



  public SQLiteHelper(Context context, String name,

    CursorFactory factory, int version) {

   super(context, name, factory, version);

  }



  @Override

  public void onCreate(SQLiteDatabase db) {


   db.execSQL(SCRIPT_CREATE_DATABASE);

  }



  @Override

  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


  }

 } 

}

这是我的一个具有数据库 ListView 的 xml

<?xml version="1.0" encoding="utf-8"?>
   <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:layout_gravity="top|center_horizontal" android:background="@drawable/bbg" >

   <TableRow android:layout_height="80px" android:layout_width="wrap_content" android:orientation="horizontal">

<Button android:id="@+id/lf_left" android:text="Previous" android:layout_width="0dip" android:height="60px" android:layout_weight="1" android:background="@drawable/custom_button"></Button>
<Button android:id="@+id/lf_right" android:text="Next" android:layout_width="0dip" android:height="60px" android:layout_weight="1" android:background="@drawable/custom_button"></Button>
</TableRow>




<TableRow android:paddingTop="20px" android:layout_width="fill_parent" android:layout_height="200px" android:orientation="vertical" android:gravity="center_horizontal|center_vertical">
<EditText

   android:id="@+id/lefttext"

   android:layout_width="300px"

   android:layout_height="wrap_content"

   />

</TableRow>
<TableRow android:paddingTop="5px" android:paddingBottom="20px" android:width="100px" android:layout_height="200px" android:orientation="vertical" android:gravity="center_horizontal|center_vertical">

   <Button android:id="@+id/lefttalkbutton" android:text="TALK" android:width="100px" android:layout_width="100px" android:background="@drawable/custom_button"></Button>
</TableRow>


<TableRow android:orientation="vertical" android:gravity="center_horizontal" android:width="200px"    layout_height="fill_parent" layout_width="fill_parent">

<ListView

 android:id="@+id/contentlist"

 android:layout_width="fill_parent"  android:width="200px" 

 android:layout_height="fill_parent" android:cacheColorHint="#00000000"/>
 </TableRow>

 </TableLayout>

这是 ListView 中每一行的 xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="@+id/id" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
 </LinearLayout>

对于 ListView 中的每个按钮,我想为该按钮添加一个 Action 监听器,该监听器接收按钮的文本并将其打印出来或 toast 。非常感谢您的帮助。 谢谢。

最佳答案

onTouch方法有一个 View 参数,它是对触摸 View 的引用。

     public void onClick(View v) 
     {
       Button b = (Button)v;
       String buttonText = b.getText().toString();
     }

这将为您提供按钮的文本。

执行 toast 很简单,看看this

关于android - ListView 项目/按钮android的actionlistener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8462172/

相关文章:

Android 蓝牙 我在哪里可以获得 UUID?

android.widget.RelativeLayout$LayoutParams 无法转换为 android.widget.AbsListView$LayoutParams

android - 如何在 DialogFragment 中设置肯定/否定按钮?

button - 为新的行 flutter 创建按钮

android - 无法解析 Widget.MaterialComponents.TextInputLayout.*.ExposedDropdownMenu

sql-server - 合并 vs Sargability

Mysql sleep 命令长时间锁定这么多行

javascript - 防止 Postgres 中的更新冲突

swift - 填充 Collection View 时如何判断是否选择了 Collection View 标题中的按钮?

android - FileTransfer Cordova下载路径