Tecnologia do Blogger.
RSS

Re: [androidbrasil-dev] Button em ListView

Essa é uma das formas de tratar eventos em uma ListView com vários itens (position, id) é diferente do evento button void onClick(View v). Desculpe se entendi errado.
Aqui vai o código inteiro de um app teste de reconhecimento de fala e envio de sms, faz uso de pequenos ícones (int [] flags) .png no ListView.

import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import java.util.HashMap;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TableRow;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebSettings;

import android.net.Uri;
import android.content.Context;
 
public class MainActivity extends Activity {
 private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;

 private ListView mlvTextMatches;
 private Spinner msTextMatches;
 private ImageButton mbtSpeak;
 private WebView webView1;
 private int noOfMatches;
 
 private String adsenseurl = "";
 
//Array of integers points to images stored in /res/drawable-ldpi/
 int[] flags = new int[]{
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon,
     R.drawable.sms_icon
 };
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 
  mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
  msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
  mbtSpeak = (ImageButton) findViewById(R.id.btSpeak);
  webView1 = (WebView) findViewById(R.id.webkit1);
  msTextMatches.setSelection(4);
  noOfMatches = 5;
  checkVoiceRecognition();
  listclick();
    webView1.loadUrl(adsenseurl);
    webView1.setBackgroundColor(0x00000000);

    WebSettings webSettings = webView1.getSettings();
    webSettings.setJavaScriptEnabled(true);
 }
 
 public void checkVoiceRecognition() {
  // Check if voice recognition is present
  PackageManager pm = getPackageManager();
  List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
    RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
  if (activities.size() == 0) {
   mbtSpeak.setEnabled(false);
   Toast.makeText(this, "Voice recognizer not present",
     Toast.LENGTH_SHORT).show();
  }
 }
 
 public void speak(View view) {
  Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
 
  // Specify the calling package to identify your application
  intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
    .getPackage().getName());
 
 
  // Given an hint to the recognizer about what the user is going to say
  //There are two form of language model available
  //1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases
  //2.LANGUAGE_MODEL_FREE_FORM  : If not sure about the words or phrases and its domain.
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
    RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
 
  // If number of Matches is not selected then return show toast message
  if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
   Toast.makeText(this, "Please select No. of Matches from spinner",
     Toast.LENGTH_SHORT).show();
   return;
  }
 
  noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
    .toString());
  // Specify how many results you want to receive. The results will be
  // sorted where the first result is the one with higher confidence.
  intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
  //Start the Voice recognizer activity for the result.
  startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
 }
 
 
 
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
 
   //If Voice recognition is successful then it returns RESULT_OK
   if(resultCode == RESULT_OK) {
 
    ArrayList<String> textMatchList = data
    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
 
    if (!textMatchList.isEmpty()) {
     // If first Match contains the 'search' word
     // Then start web search.
     if (textMatchList.get(0).contains("search")) {
 
        String searchQuery = textMatchList.get(0);
        searchQuery = searchQuery.replace("search","");
        Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
        search.putExtra(SearchManager.QUERY, searchQuery);
        startActivity(search);
     } else {
        
        // Keys used in Hashmap
         String[] from = { "flag","txt" };
 
         // Ids of views in listview_layout
         int[] to = { R.id.flag,R.id.txt };
        
         List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
        
         for(int i=0;i < noOfMatches;i++){
         HashMap<String, String> hm = new HashMap<String,String>();    
         hm.put("txt", textMatchList.get(i) );
         hm.put("flag", Integer.toString(flags[0]) );
         aList.add(hm);
         }
        
         SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);    
        
         mlvTextMatches.setAdapter(adapter);
        
         noOfMatches = 0;
     }
 
    }
   //Result code for various error.
   }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
    showToastMessage("Audio Error");
   }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
    showToastMessage("Client Error");
   }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
    showToastMessage("Network Error");
   }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
    showToastMessage("No Match");
   }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
    showToastMessage("Server Error");
   }
  super.onActivityResult(requestCode, resultCode, data);
 }
 
 
 /**
 * Helper method to show the toast message
 **/
 protected void showToastMessage(String message){
  Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
 }

 
  protected void listclick() {
  mlvTextMatches.setOnItemClickListener(new OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              String value = mlvTextMatches.getItemAtPosition(position).toString();
              TextView v=(TextView) view.findViewById(R.id.txt);
              String mytext = v.getText().toString();
              sendSMS(mytext);
             }
    });
  }
 
 
 
  protected void sendSMS(String msg) {
     
      Intent intent = new Intent(Intent.ACTION_VIEW);         
      intent.setData(Uri.parse("sms:"));
      intent.putExtra("sms_body", msg);
      startActivity(intent);      
     

  }
 
 

}

 


Em 4 de outubro de 2013 14:44, Gleydson Rocha <gwrocha91@gmail.com> escreveu:
http://pastebin.com/AJLL5Efi

Olaá Pedro, Colequei o codigo aí!

Só detalhando um pouco mais, no metodo onClick ele faz uma ação com o webservice que esta dando tudo certo, o problema é que quando eu mudo o background desse button ele muda de outros buttons tbm, mais precisamente sempre altenando um(um sim outro não).

Marcelo não consegui entender direito sua sugestão.

Gleydson Rocha
Graduando em Ciência da Computação - UESPI


Em 4 de outubro de 2013 11:31, marcelo yonamine <yonamine60@gmail.com> escreveu:
Esta parte do código pega o texto de uma listview pegando a posição (position) onde o usuário tocou no item da lista.
onde mlvTextMatches é o ListView
lembrando que a função listclick() esta dentro de um  @Override
protected void listclick() {
  mlvTextMatches.setOnItemClickListener(new OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              String value = mlvTextMatches.getItemAtPosition(position).toString();
              TextView v=(TextView) view.findViewById(R.id.txt);
              String mytext = v.getText().toString();
              sendSMS(mytext);
             }
    });
  }


Em 4 de outubro de 2013 09:50, Pedro Subutzki <Pepeu> <falecompepeu@gmail.com> escreveu:

Você precisa identificar o item do list view para atribuir a ação ao botão.
Mande o código que você fez para que possamos apontar onde pode estar o erro.

Se possível use o http://pastebin.com/

Abraços,
Pedro Subutzki
__________________________________________
HADI - Makes SQLite in Android easy and simple
https://github.com/PepeuCps/Hadi


Em 3 de outubro de 2013 17:26, Gleydson Rocha <gwrocha91@gmail.com> escreveu:

Olá Galera!

Eu tenho um Button dentro de uma ListView e consegui atribuir um listener pra ele. Mas quando eu clico em um botão a msm ação acontece em vários botões da lista.

Alguém já passou por isso ou tem alguma sugestão?

Gleydson Rocha
Graduando em Ciência da Computação - UESPI

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

0 comentários:

Postar um comentário