I'm having some problems to figure out how I can implement '.setOnItemClickListener' in a GitHub sample project for Android.
I want to select the cells of a list view, but I can get it to work. The github project is this:
https://github.com/schrockblock/android-table-view
I'm trying to add the listener in my main activity but I can't. Here is the code:
public class MainActivity extends ActionBarActivity {
public String[] items={};
WifiHelper wifiHelper;
List<ScanResult> list;
//public WifiManager pWifiManager;
ListView tableView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 取得WifiManager对象
//pWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiHelper = new WifiHelper(this);
//open wifi
wifiHelper.openWifi(new WifiHelper.openWifiCallback() {
#Override
public void openSuccess() {
//open success
}
#Override
public void openFail() {
//open fail
}
});
//scan wifi
list = wifiHelper.startScan();
tableView = (ListView)findViewById(R.id.table_view);
TableViewDataSource tvds = new TableViewDataSource(this){
#Override
protected int numberOfSections() {
return 3;
}
#Override
protected String titleForHeaderInSection(int section) {
if(section==0)
return "\nGENERAL";
else if(section==1)
return "Pull down to refresh networks information ot tap 'Scan' button in the top bar of the screen.\n\nNETWORKS";
else
return "Networks under -75dB (RSSI) may have connectivity problems. Try to be as near as you can of the network.\n\nOnly supported networks can use the exploit feature of this app. You can use iWepPRO as your wifi manager application";
}
#Override
protected int numberOfRowsInSection(int section){
if(section==0)
return 3;
else if(section==1)
return list.size();
else
return 1;
}
#Override
protected DefaultCell cellForRowAtIndexPath(JIndexPath indexPath) {
if(indexPath.section==0) {
DefaultCell cell = new DefaultCell();
cell.hashIBencryption = true;
cell.imageButtonImage = R.drawable.emptywhite2px;
switch (indexPath.row){
case 0:
cell.textLabelText = "WiFi";
cell.hasDisclosureIndicator = false;
cell.hasDisclosureIndicator2 = false;
cell.hasSwitch = true;
cell.hasSwitchOn = true;
break;
case 1:
cell.textLabelText = "Auto-Scan";
cell.hasDisclosureIndicator = false;
cell.hasDisclosureIndicator2 = false;
cell.hasSwitch = true;
cell.hasSwitchOn = false;
break;
case 2:
cell.textLabelText = "Information";
cell.hasDisclosureIndicator = true;
cell.hasDisclosureIndicator2 = false;
break;
default:
break;
}
return cell;
}else if(indexPath.section==1){
SubtitleCell cell1 = new SubtitleCell();
cell1.hasDisclosureIndicator = false;
cell1.hasDisclosureIndicator2 = true;
cell1.hashIBencryption = true;
//cell1.textLabelText = "network name " + indexPath.row;
ScanResult r = list.get(indexPath.row);
//String ssidName = r.SSID;
cell1.textLabelText = r.SSID;
//cell1.detailTextLabelText = "signal " + indexPath.row;
cell1.detailTextLabelText = "" + r.level;
//cell1.detailTextLabelText = "" + calculateSignalStength(pWifiManager, r.level);
cell1.imageButtonImage = R.drawable.deviceaccesssecure;
return cell1;
}else if(indexPath.section==2){
SubtitleCell cell2 = new SubtitleCell();
cell2.hashIBencryption = true;
cell2.imageButtonImage = R.drawable.emptywhite2px;
cell2.textLabelText = " ";
cell2.hasDisclosureIndicator2 = false;
cell2.hasDisclosureIndicator = false;
cell2.hasEmptyCell = true;
return cell2;
}
return null;
}
};
tableView.setAdapter(tvds);
}
I have read and test some samples coding the setOnItemClickListener after the 'setAdapter()' function, but it does not work.
I 'm trying to set the cell selection to show a Toast with some text in order to see if it works, but I don't know what I'm doing wrong.
Can anyone help me with some tips??
Thank you very much in advance.
These are my two layouts:
Cell Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:padding="0dp"
android:background="#ffdedede">
<TextView
android:id="#+id/header_text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textSize="12dp"
android:textColor="#android:color/darker_gray"
android:padding="0dp"
android:visibility="gone"
android:layout_marginLeft="20dp"
android:typeface="sans"
android:layout_marginRight="20dp"
android:elegantTextHeight="false" />
<RelativeLayout
android:id="#+id/rl2"
android:layout_centerVertical="true"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:layout_below="#+id/header_text_view"
android:padding="0dp"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/rl3"
android:layout_centerVertical="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="0dp"
android:background="#android:color/white">
<TextView android:id="#+id/title_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cell Title"
android:textSize="18sp"
android:textColor="#000"
android:background="#0fff"
android:paddingTop="5dp"
android:paddingLeft="5dp"
android:paddingBottom="2dp"
android:typeface="sans"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ibencryption"
android:layout_toEndOf="#+id/ibencryption" />
<TextView
android:id="#+id/detail_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cell Subtitle"
android:paddingLeft="5dp"
android:paddingBottom="5dp"
android:textColor="#555"
android:background="#0fff"
android:textSize="14sp"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/ibencryption"
android:layout_toEndOf="#+id/ibencryption" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ibencryption"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:layout_alignParentTop="true"
android:background="#android:color/white"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"
android:adjustViewBounds="false" />
</RelativeLayout>
<ImageView
android:id="#+id/disclosure_indicator"
android:src="#drawable/nextitem"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginRight="20dp"
android:cropToPadding="true"/>
<ImageView
android:id="#+id/disclosure_indicator_2"
android:src="#drawable/actionabout"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginRight="20dp"
android:cropToPadding="true"/>
<Switch
android:id="#+id/switch_indicator"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginRight="20dp"
android:cropToPadding="true"/>
</RelativeLayout>
And the main activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/table_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Thank you!!
This is how you can provide a OnItemClickListener :
tableView.setOnItemClickListener(new OnItemClickListener(){
void onItemClick(AdapterView<?> parent, View view, int position, long id){
switch(position){
default: Toast.makeToast(MainActivity.this, "Some crappy text",Toast.LENGTH_LONG ).show();
}
}
}};
Generally :
First of all put all your View#findViewById(int) code to the top of your OnCreate method just below your Activity#setContentView(int) call.
Then try to scan in your WifiManager#openSuccess() callback..
Try to refactor your code and replace all your if,else if and else blocks which check against an integer with switch blocks.
And please do not return null EVER.
Related
I have Pager Adapter that initialize Fragment list. Problem is that Fragment loading very slow. It has delay of couple seconds, than start do load data.
I have parsed data from URL in AsyncTask doInBackground() and worked with UI in AsyncTask onPosteExecute()
Here is my Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
readBundle(getArguments());
v = inflater.inflate(R.layout.fragment_fragment1, container, false);
new asyncTekstovi().execute(result);
return v;
}
public class asyncTekstovi extends AsyncTask<String, ArrayList<String>, ArrayList<String>> {
String result;
#Override
protected ArrayList<String> doInBackground(String... params)
{
try {
result = Ion.with(getActivity().getApplicationContext())
.load(FragmentNewsReader.this.result)
.asString()
.get();
} catch (Exception e){
e.printStackTrace();
}
String pasusUTekstu="";
if (result != null){
String htmlStringTekst=result.substring(result.indexOf("<!-- BEGIN .shortcode-content -->"), result.length());
int startPositionTekst=htmlStringTekst.indexOf("<div class=\"shortcode-content\">");
int endPositionTekst=startPositionTekst+"<div class=\"shortcode-content\">".length();
while(htmlStringTekst.substring(startPositionTekst,endPositionTekst).indexOf("<!-- END .shortcode-content -->")<0){
endPositionTekst++;
}
htmlStringTekst=htmlStringTekst.substring(startPositionTekst,endPositionTekst);
//System.out.println("vladica:"+htmlStringTekst.length()+htmlStringTekst);
int poc1;
int kraj1;
while((poc1=htmlStringTekst.indexOf("<div id"))>=0){
//System.out.println("poc1="+poc1);
kraj1=poc1+"<div id".length();
while(htmlStringTekst.substring(poc1,kraj1).indexOf(">")<0){
//System.out.println("seckanje:"+htmlStringTekst.substring(poc1,kraj1));
kraj1++;
}
htmlStringTekst=htmlStringTekst.replace(htmlStringTekst.substring(poc1,kraj1),"<p>");
}
while((poc1=htmlStringTekst.indexOf("<p "))>=0){
kraj1=poc1+"<p ".length();
while(htmlStringTekst.substring(poc1,kraj1).indexOf(">")<0){
kraj1++;
}
htmlStringTekst=htmlStringTekst.replace(htmlStringTekst.substring(poc1,kraj1),"<p>");
}
htmlStringTekst=htmlStringTekst.replace("<div id","<p>");
htmlStringTekst=htmlStringTekst.replace("</div>","</p>");
htmlStringTekst=htmlStringTekst.replace(" ","");
while(htmlStringTekst.length()>0){
startPositionTekst=htmlStringTekst.indexOf("<p>");
if(startPositionTekst>=0){
startPositionTekst+="<p>".length();
endPositionTekst=startPositionTekst;
while (htmlStringTekst.substring(startPositionTekst, endPositionTekst).indexOf("</p>") < 0) {
endPositionTekst++;
}
if(pasusUTekstu.indexOf("<img")<0) {
if(pasusUTekstu.length()>5) pasusUTekstu+="\n\n";
pasusUTekstu += htmlStringTekst.substring(startPositionTekst, endPositionTekst); //e sad ja...
}
else {
pasusUTekstu=htmlStringTekst.substring(startPositionTekst,endPositionTekst);
}
htmlStringTekst = htmlStringTekst.substring(endPositionTekst);
pasusUTekstu = pasusUTekstu.replace("<strong>", "");
pasusUTekstu = pasusUTekstu.replace("</strong>", "");
int poc=pasusUTekstu.indexOf("<img");
int zastavica=0;
if(poc>=0) zastavica=1;
while(poc>=0) {
int kraj = poc;
while (pasusUTekstu.substring(poc, kraj).indexOf("/>") < 0) {
kraj++;
}
String link = pasusUTekstu.substring(poc, kraj);
pasusUTekstu = pasusUTekstu.replace(link, "");
poc = pasusUTekstu.indexOf("<img");
}
poc=pasusUTekstu.indexOf("<a href=");
while(poc>=0) {
int kraj = poc;
while (pasusUTekstu.substring(poc, kraj).indexOf(">") < 0) {
kraj++;
}
String link = pasusUTekstu.substring(poc, kraj);
pasusUTekstu = pasusUTekstu.replace(link, "");
poc = pasusUTekstu.indexOf("<a href=");
}
pasusUTekstu=pasusUTekstu.replace("&","&");
pasusUTekstu=pasusUTekstu.replace("–","-");
pasusUTekstu=pasusUTekstu.replace("“","\"");
pasusUTekstu=pasusUTekstu.replace("”","\"");
pasusUTekstu=pasusUTekstu.replace("<p>","");
pasusUTekstu=pasusUTekstu.replace("</a>","");
pasusUTekstu=pasusUTekstu.replace("<br />","");
pasusUTekstu=pasusUTekstu.replace("</p>","");
pasusUTekstu=pasusUTekstu.replace(" ","");
pasusUTekstu=pasusUTekstu.replace("\n\n\n","\n");
//pasusUTekstu=pasusUTekstu.replace("\n\n","\n");
//System.out.println("pocetak je:"+ pasusUTekstu);
if(zastavica==1) {
if(pasusUTekstu.substring(pasusUTekstu.length()-2).equals("\n\n")) pasusUTekstu=pasusUTekstu.substring(0,pasusUTekstu.length()-2);
listaTeksta.add(pasusUTekstu);
pasusUTekstu="";
zastavica=0;
}
}
else break;
}
}
if(pasusUTekstu.length()>5) listaTeksta.add(pasusUTekstu);
return listaTeksta;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
String rezultat = "";
for(int i=0;i<listaSlika.size() ;i++) {
v.findViewById(mLayoutIdArray[i]).setVisibility(View.VISIBLE);
}
for(int i=0;i<result.size();i++) {
textTv[i] = (TextView) v.findViewById(nizTekstaID[i]);
textTv[i].setText(result.get(i));
}
}
protected void onPreExecute() {
}
}
Here is my XML:
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/vestGlavnaSlikaLayout"
android:layoutDirection="ltr"
android:elevation="10dp">
<ImageView
android:id="#+id/glavnaSlika"
android:layout_width="match_parent"
android:fitsSystemWindows="false"
android:scaleType="fitXY"
android:focusable="false"
android:cropToPadding="false"
android:adjustViewBounds="true"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="false"
android:layout_alignParentEnd="false"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/layouttekstglavnevesti1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#android:drawable/screen_background_dark_transparent"
android:padding="0dp">
<TextView
android:id="#+id/naslovglavni"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:padding="10dp"
android:textColor="#android:color/background_light"
android:textSize="36sp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lazoutZaNaslove"
android:layout_marginBottom="15dp"
android:layout_marginLeft="#dimen/h"
android:layout_marginRight="#dimen/h"
android:layout_marginTop="-10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/prednaslov"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/darker_gray"
android:layout_marginLeft="-40dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/naslov1"
android:textSize="20sp"
android:textColor="#android:color/black"
android:textStyle="normal|bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/podnaslov"
android:textColor="#android:color/black"
android:textSize="15sp"
android:textStyle="normal|bold" />
</LinearLayout>
<include
layout="#layout/activity_slikatext1"
android:id="#+id/includedLayout"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/h"
android:layout_marginRight="#dimen/h"
android:layout_below="#id/lazoutSlikaTekst" />
<include
layout="#layout/activity_slikatext2"
android:id="#+id/includedLayout1"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/h"
android:layout_marginRight="#dimen/h"
android:layout_below="#id/includedLayout" />
<include
layout="#layout/activity_slikatext3"
android:id="#+id/includedLayout2"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/h"
android:layout_marginRight="#dimen/h"
android:layout_below="#id/includedLayout1" />
<include
layout="#layout/activity_slikatext4"
android:id="#+id/includedLayout3"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/h"
android:layout_marginRight="#dimen/h"
android:layout_below="#id/includedLayout2" />
<include
layout="#layout/activity_slikatext5"
android:id="#+id/includedLayout4"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/h"
android:layout_marginRight="#dimen/h"
android:layout_below="#id/includedLayout3" />
Change this code to onViewCreated() method
new asyncTekstovi().execute(result);
i want get image from the listview .But problem is that whatever the list view i created that is not clickable. i tried with onItemclick listener also, but its not working because of listview is not clickable . Its seems that listview is not at all clickable ..Below is given adapter for for listview.
// The adapter of the GridView which contains the details of the detected faces.
private class FaceListAdapter extends BaseAdapter {
//List<FaceRectangle> ffRect;
// The detected faces.
List<Face> faces;
List<UUID> faceIdList;
List<IdentifyResult> mIdentifyResults;
// The thumbnails of detected faces.
List<Bitmap> faceThumbnails;
// Initialize with detection result.
FaceListAdapter(Face[] detectionResult) {
//ffRect=new ArrayList<>();
faceIdList = new ArrayList<>();
faces = new ArrayList<>();
faceThumbnails = new ArrayList<>();
mIdentifyResults = new ArrayList<>();
if (detectionResult != null) {
faces = Arrays.asList(detectionResult);
for (Face face: faces) {
try {
// Crop face thumbnail with five main landmarks drawn from original image.
faceThumbnails.add(ImageHelper.generateFaceThumbnail(mBitmap, face.faceRectangle));
faceRect=face.faceRectangle;
//ffRect.add(faceRect);
faceIdList.add(null);
} catch (IOException e) {
// Show the exception when generating face thumbnail fails.
//setInfo(e.getMessage());
}
}
}
}
public void setIdentificationResult(IdentifyResult[] identifyResults) {
mIdentifyResults = Arrays.asList(identifyResults);
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public int getCount() {
return faces.size();
}
#Override
public Object getItem(int position) {
return faces.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_face_with_description, parent, false);
}
convertView.setId(position);
// Show the face thumbnail.
((ImageView)convertView.findViewById(R.id.face_thumbnail)).setImageBitmap(faceThumbnails.get(position));
if (mIdentifyResults.size() == faces.size()) {
// Show the face details.
DecimalFormat formatter = new DecimalFormat("#0.00");
if (mIdentifyResults.get(position).candidates.size() > 0) {
String personId = mIdentifyResults.get(position).candidates.get(0).personId.toString();
String personName = StorageHelper.getPersonName(personId, "person", Face_detection.this);
String identity = "Person: " + personName + "\n" + "Confidence: " + formatter.format(mIdentifyResults.get(position).candidates.get(0).confidence);
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(identity);
photoAdd.setEnabled(false);
} else {
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(
R.string.face_cannot_be_identified);
photoAdd.setEnabled(true);
// btmp.add(faceThumbnails.get(position));
//fRect.add(ffRect.get(position));
}
}
return convertView;
}
}
> item_face_with_description.xml
<!-- Copyright (c) Microsoft. All rights reserved. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/face_thumbnail"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:id="#+id/text_detected_face" />
</LinearLayout>
Xml that contains ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_face_detection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="myapptest.techm.com.myapptest.Face_detection">
<include
android:id="#+id/tool_bar"
layout="#layout/tacho_toolbar"></include>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/tool_bar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Take Again"
android:layout_height="wrap_content"
android:layout_marginTop="22dp"
android:id="#+id/takePhoto"
android:layout_below="#+id/camerapreview"
android:layout_centerHorizontal="true"
android:layout_width="150dp"
android:onClick="clickPhoto (Face_detection)"
android:visibility="gone" />
<TextView
android:text="Faces in Image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView23"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_below="#+id/takePhoto"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
<ListView
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_below="#+id/textView23"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="28dp"
android:id="#+id/face_detect_list"
android:focusable="false" />
<Button
android:text="Add"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:layout_marginBottom="103dp"
android:id="#+id/photoAdd" />
<Button
android:text="Cancle"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/photoAdd"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="66dp"
android:layout_marginEnd="66dp"
android:id="#+id/cancle" />
<SurfaceView
android:id="#+id/camerapreview"
android:layout_width="350dp"
android:layout_height="400dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Button
android:text="Identify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/cancle"
android:layout_alignRight="#+id/takePhoto"
android:layout_alignEnd="#+id/takePhoto"
android:layout_marginRight="18dp"
android:layout_marginEnd="18dp"
android:id="#+id/identify"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
The isEnabled method on your adapter is responsible for your ListView ignoring clicks.
#Override
public boolean isEnabled(int position)
{
return false;
}
Your adapter overrides isEnabled and returns false for all positions, indicating that every item in the list is disabled. Disabled views do not receive input events.
If its possible to disable items in your list then your custom adapter needs to track these items somehow (e.g. a list), otherwise you should be returning true for all positions.
In the Android app I'm developing I'm loading a list of several items for the user to input some data; there's a checkbox and an EditText for each item, and the user can check the checkbox and type some notes regarding the item. This list is loaded dynamically from a local database, which in turn is populated from a remote database at a previous point. Now, the problem I'm having is that, whenever I focus on an EditText, after I lose focus on the element, the list seems to load again (elements which where unchecked/blank originally and had been checked/had text typed in them become unchecked/blank again, and those which were checked/had text initially go back to the original state). This only happens when I lose focus on the EditText; I can check and uncheck the checkboxes and they stay how I leave them (until I get and lose focus on an EditText). How can I avoid this so my elements retain the data?
I've tested the app in deviced with Android versions 3.2 and 4.2
Any help would be appreciated.
Here's the activity that loads the list:
public class PostventaPreentregaDetalleActivity extends Activity implements OnItemClickListener, OnItemSelectedListener {
private ArrayList<EncuestaPostventa> listaChequeoEncuesta;
private ArrayList<ConsumoBien> listaConsumoBien;
private ListView lvChequeoEncuesta;
private ListView lvConsumoBien;
private EncuestaPostventaAdapter adapter;
private ConsumoBienAdapter adapterConsumoBien;
public static DBProvider oDB;
#Override
public void onBackPressed() {
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.postventa_preentrega_detalle_activity_actions, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
getActionBar().setDisplayHomeAsUpEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postventa_preentrega_detalle);
listaChequeoEncuesta = new ArrayList<EncuestaPostventa>();
listaConsumoBien = new ArrayList<ConsumoBien>();
inicializarPestanas();
cargarDetalleNegocio();
listarChequeoEncuesta();
listarConsumoBien();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onItemClick(AdapterView<?> adapter, View view, int position,
long ID) {
}
public void cargarDetalleNegocio(){
Intent intent = getIntent();
TextView tvProyecto;
TextView tvCliente;
TextView tvRut;
TextView tvDireccion;
tvProyecto = (TextView) findViewById(R.id.tvProyecto);
tvRut = (TextView) findViewById(R.id.tvRut);
tvCliente = (TextView) findViewById(R.id.tvCliente);
tvDireccion = (TextView) findViewById(R.id.tvDireccion);
tvProyecto.setText(intent.getStringExtra("proyecto").trim());
tvRut.setText(intent.getStringExtra("rut").trim());
tvCliente.setText(intent.getStringExtra("cliente").trim());
tvDireccion.setText(intent.getStringExtra("direccion").trim());
}
public void inicializarPestanas(){
TabHost tabs = (TabHost)findViewById(android.R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec("tabChequeo");
spec.setContent(R.id.tabChequeo);
spec.setIndicator("Chequeo");
tabs.addTab(spec);
spec = tabs.newTabSpec("tabServicios");
spec.setContent(R.id.tabServicios);
spec.setIndicator("Servicios consumidos");
tabs.addTab(spec);
spec = tabs.newTabSpec("tabObservaciones");
spec.setContent(R.id.tabObservaciones);
spec.setIndicator("Observaciones");
tabs.addTab(spec);
tabs.setCurrentTab(0);
}
public void listarChequeoEncuesta(){
try{
oDB = new DBProvider(this);
Intent intent = getIntent();
int idBien = intent.getIntExtra("id_bien", 0);
int idEncuestaPreentrega = intent.getIntExtra("id_encuestapreentrega", 0);
String[][] arrayChequeoEncuesta = oDB.traerEncuestaPostventa(idBien,
idEncuestaPreentrega);
if(!(arrayChequeoEncuesta == null)){
for(int i=0; i<arrayChequeoEncuesta.length; i++){
int idEncuestaPostventa = Integer.parseInt(arrayChequeoEncuesta[i][0]);
int idEncuestaDetalle = Integer.parseInt(arrayChequeoEncuesta[i][1]);
String item = arrayChequeoEncuesta[i][2];
Boolean recepcion = (Integer.parseInt(arrayChequeoEncuesta[i][3]) != 0);
String observacion =arrayChequeoEncuesta[i][4];
listaChequeoEncuesta.add(new EncuestaPostventa(idEncuestaPostventa,
idEncuestaDetalle,
item,
recepcion,
observacion));
}
}
adapter = new EncuestaPostventaAdapter(this, listaChequeoEncuesta);
lvChequeoEncuesta = (ListView) findViewById(R.id.lvChequeoEncuesta);
lvChequeoEncuesta.setAdapter(adapter);
}catch(Exception e){
Toast.makeText(this, "Error (listarChequeoEncuesta): " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void listarConsumoBien(){
try{
oDB = new DBProvider(this);
Intent intent = getIntent();
int argIdBien = intent.getIntExtra("id_bien", 0);
int argIdEmpsa = intent.getIntExtra("id_empsa", 0);
String[][] arrayConsumoBien = oDB.traerConsumoBien(argIdBien,
argIdEmpsa);
if(!(arrayConsumoBien == null)){
for(int i=0; i<arrayConsumoBien.length; i++){
int idConsumoBien = Integer.parseInt(arrayConsumoBien[i][0]);
int idBien = Integer.parseInt(arrayConsumoBien[i][1]);
int idDominio = Integer.parseInt(arrayConsumoBien[i][2]);
String nombre = arrayConsumoBien[i][3];
String unidad = arrayConsumoBien[i][4];
int cantidad = Integer.parseInt(arrayConsumoBien[i][5]);
Boolean estado = (Integer.parseInt(arrayConsumoBien[i][6]) != 0);
listaConsumoBien.add(new ConsumoBien(idConsumoBien,
idBien,
idDominio,
nombre,
unidad,
cantidad,
estado));
}
}
adapterConsumoBien = new ConsumoBienAdapter(this, listaConsumoBien);
lvConsumoBien = (ListView) findViewById(R.id.lvConsumoBien);
lvConsumoBien.setAdapter(adapterConsumoBien);
}catch(Exception e){
Toast.makeText(this, "Error (listarConsumoBien): " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
public void onNothingSelected(AdapterView<?> parent)
{
}
}
And its layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:parentActivityName="net.gestionwireless.officemovil.inmobiliario.PostventaPreentregaActivity">
<TabHost android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelProyecto"
android:text="#string/proyecto"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvProyecto"
android:text=""
android:layout_toRightOf="#id/tvLabelProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelRut"
android:layout_below="#id/tvLabelProyecto"
android:text="#string/rut"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvRut"
android:text=""
android:layout_toRightOf="#id/tvLabelRut"
android:layout_below="#id/tvProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelCliente"
android:layout_marginLeft="50dp"
android:layout_below="#id/tvLabelProyecto"
android:layout_toRightOf="#id/tvRut"
android:text="#string/cliente" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvCliente"
android:text=""
android:layout_toRightOf="#id/tvLabelCliente"
android:layout_below="#id/tvProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelDireccion"
android:layout_below="#id/tvCliente"
android:text="#string/direccion"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvDireccion"
android:text=""
android:layout_toRightOf="#id/tvLabelDireccion"
android:layout_below="#id/tvCliente" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tvDireccion">
<TabWidget android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs" />
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent">
<LinearLayout
android:id="#+id/tabChequeo"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:text="#string/titulo_grilla_item"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_recepcion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_observacion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".57"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lvChequeoEncuesta"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
</LinearLayout>
<LinearLayout
android:id="#+id/tabServicios"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:text="#string/titulo_grilla_servicio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".4"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_recepcion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_consumo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_unidad"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".2"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lvConsumoBien"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
</LinearLayout>
<LinearLayout android:id="#+id/tabObservaciones"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/etObservaciones"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hint_observaciones" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</TabHost>
</LinearLayout>
The class for each item:
package net.gestionwireless.officemovil.inmobiliario;
public class EncuestaPostventa {
private int idEncuestaPostventa;
private int idEncuestaDetalle;
private String item;
private Boolean recepcion;
private String observacion;
public EncuestaPostventa(int idEncuestaPostventa,
int idEncuestaDetalle,
String item,
Boolean recepcion,
String observacion) {
this.idEncuestaPostventa = idEncuestaPostventa;
this.idEncuestaDetalle = idEncuestaDetalle;
this.item = item;
this.recepcion = recepcion;
this.observacion = observacion;
}
public int traerIdEncuestaPostventa() {
return idEncuestaPostventa;
}
public void asignarIdEncuestaPostventa(int idEncuestaPostventa) {
this.idEncuestaPostventa = idEncuestaPostventa;
}
public int traerIdEncuestaDetalle() {
return idEncuestaDetalle;
}
public void asignarIdEncuestaDetalle(int idEncuestaDetalle) {
this.idEncuestaDetalle = idEncuestaDetalle;
}
public String traerItem() {
return item;
}
public void asignarItem(String item) {
this.item = item;
}
public Boolean traerRecepcion() {
return recepcion;
}
public void asignarRecepcion(Boolean recepcion) {
this.recepcion = recepcion;
}
public String traerObservacion() {
return observacion;
}
public void asignarObservacion(String observacion) {
this.observacion = observacion;
}
}
package net.gestionwireless.officemovil.inmobiliario;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
The adapter:
public class EncuestaPostventaAdapter extends ArrayAdapter<EncuestaPostventa> {
private Context context;
private ArrayList<EncuestaPostventa> datos;
public EncuestaPostventaAdapter(Context context, ArrayList<EncuestaPostventa> datos) {
super(context, R.layout.encuestapostventa_item, datos);
this.context = context;
this.datos = datos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = LayoutInflater.from(context).inflate(
R.layout.encuestapostventa_item, null);
TextView tvItem = (TextView) item.findViewById(R.id.tvItem);
tvItem.setText(datos.get(position).traerItem());
CheckBox chkRecepcion = (CheckBox) item.findViewById(R.id.chkRecepcion);
chkRecepcion.setChecked(datos.get(position).traerRecepcion());
EditText editObservacion = (EditText) item.findViewById(R.id.editObservacion);
editObservacion.setText(datos.get(position).traerObservacion());
return item;
}
}
And the layout for each item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="horizontal">
<TextView
android:id="#+id/tvItem"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".33"
android:textSize="#dimen/texto_L" />
<CheckBox
android:id="#+id/chkRecepcion"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".1"/>
<EditText
android:id="#+id/editObservacion"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".57"
android:textSize="#dimen/texto_L"
android:inputType="textCapSentences" />
</LinearLayout>
If you put a log statement in your ArrayAdapter.getView(), you'll realize what's going on in two seconds.
As the list is scrolled, a list item that you edited is scrolled out of view. When the item is scrolled back into view, the view is recreated and getView() is called. Since your adapter doesn't have a representation of the changes that were made previously, getView() recreates the view with the original unedited data.
If that's happening to you on focus lost, that must mean that the focus-lost event is triggering a view update on the list item. I've never done editing in a list item, so I'm not familiar with that behavior.
You need to put event listeners on your EditText and CheckBox that store their edited state somewhere. Then your adapter needs to use that edit state when creating the list items.
You might have to write a more complex adapter that extends BaseAdapter directly. The adapter is the Model for your list View, and there's no state in a ListView except for your adapter. In the case of ListView, the view can update any part of its list at any time, so the adapter has to have the current model data for the ListView at all times.
I just do my project but when I test my app I found that then I touch the screen by using more than one fingers my app may start two or three different activities.
The activities all go to the back stack. Is this a bug in Android framework? But I can't reappear this condition, it just happened.
So, have you guys ever have this problem? Please come and discuss with me. If you do; Thanks.
Supply:
And here is My xml file , when I click the different RelativeLayout at the same time , it happened.
I tried this afternoon , but this condition is not appear anymore. Now I am confusing.
<LinearLayout android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/appDefaultSingleBlockBackground"
android:layout_height="wrap_content">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="100dp"
android:clickable="true"
android:background="#drawable/mine_bg"
android:id="#+id/mine_goto_personal_info_btn"
>
<TextView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:id="#+id/mine_nick_and_avatar"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextTitle"
android:textColor="#color/appDefaultSingleBlockBackground"
android:text=""/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_interesting_venue"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_attentionbutton"
android:text="#string/myAtentionVenue"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_setting"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_setbutton"
android:text="#string/setting"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_youhuijuan"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_discountbutton"
android:text="#string/youhuijuan"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_my_rest_money"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_balancebutton"
android:text="#string/myRest"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_secure"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_accountssafebutton"
android:text="#string/secure"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/dividerdefault"
/>
</LinearLayout>
and this is my java code .
private void init(View ret) {
final TextView txtAvatar = (TextView) ret.findViewById(R.id.mine_nick_and_avatar);
final RelativeLayout gotoPersonal = (RelativeLayout) ret.findViewById(R.id.mine_goto_personal_info_btn);
RelativeLayout gotoInterest = (RelativeLayout) ret.findViewById(R.id.mine_goto_interesting_venue);
RelativeLayout gotoSetting = (RelativeLayout) ret.findViewById(R.id.mine_goto_setting);
RelativeLayout gotoYouhuijuan = (RelativeLayout) ret.findViewById(R.id.mine_goto_youhuijuan);
RelativeLayout gotoMyRestMoney = (RelativeLayout) ret.findViewById(R.id.mine_goto_my_rest_money);
RelativeLayout gotoSecure = (RelativeLayout) ret.findViewById(R.id.mine_goto_secure);
gotoPersonal.setTag("gotoPersonal");
gotoInterest.setTag("gotoInterest");
gotoSetting.setTag("gotoSetting");
gotoYouhuijuan.setTag("gotoYouhuijuan");
gotoMyRestMoney.setTag("gotoMyRestMoney");
gotoSecure.setTag("gotoSecure");
try {
Object o = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[1]);
if (o != null && !"null".equals(o)) {
txtAvatar.setText((String) o);
} else {
o = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[10]);
if (o != null && !"null".equals(o))
txtAvatar.setText("KD" + o);
}
} catch (Exception e) {
}
Object o1 = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[2]);
if (o1 != null)
MyApplication.downloader.download("http://" + o1, new ImageDownloadStateListener() {
#Override
public void loading() {
}
#Override
public void loadSuccess(Bitmap bitmap, String url) {
try {
bitmap = Tools.transforCircleBitmap(bitmap);
BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
gotoPersonal.measure(0, 0);
int measuredHeight = gotoPersonal.getMeasuredHeight();
LogHelper.print("==height" + measuredHeight);
drawable.setBounds(0, 0, measuredHeight / 5 * 4, measuredHeight / 5 * 4);
txtAvatar.setCompoundDrawables(drawable, null, null, null);
} catch (Exception e) {
//no nothing
}
}
#Override
public void loadFailed() {
}
});
gotoPersonal.setOnClickListener(this);
gotoInterest.setOnClickListener(this);
gotoSetting.setOnClickListener(this);
gotoYouhuijuan.setOnClickListener(this);
gotoMyRestMoney.setOnClickListener(this);
gotoSecure.setOnClickListener(this);
}
#Override
public void onResume() {
initActionBar();
super.onResume();
MobclickAgent.onPageStart(getClassName()); //统计页面
}
#Override
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd(getClassName());
}
private String getClassName() {
String canonicalName = this.getClass().getCanonicalName();
String[] split = canonicalName.split("\\.");
return split[split.length - 1];
}
private void initActionBar() {
MyActivity activity = (MyActivity) mActivity;
activity.setActionBarLeftImg(new ColorDrawable(Color.TRANSPARENT), false);
activity.setActionBarRightImg(new ColorDrawable(Color.TRANSPARENT));
activity.setOnActionBarLeftClickListener(null);
activity.setOnActionBarRightClickListener(null);
activity.setActionBarTitle("个人中心");
}
#Override
public void onClick(View v) {
Object tag = v.getTag();
if (tag != null) {
String str = (String) tag;
if (mActivity == null) {
return;
}
if (!((MyActivity) (mActivity)).isLogin) {
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivity(intent);
return;
}
if (!TextUtils.isEmpty(str))
if ("gotoPersonal".equals(str)) {
Intent intent = new Intent(mActivity, PersonalInfoActivity.class);
startActivity(intent);
} else if ("gotoInterest".equals(str)) {
Intent intent = new Intent(mActivity, VenueListActivity.class);
intent.putExtra("isInterests", true);
startActivity(intent);
} else if ("gotoSetting".equals(str)) {
Intent intent = new Intent(mActivity, SettingActivity.class);
startActivity(intent);
} else if ("gotoYouhuijuan".equals(str)) {
Intent intent = new Intent(mActivity, FavorableActivity.class);
startActivity(intent);
} else if ("gotoSecure".equals(str)) {
Intent intent = new Intent(mActivity, SecureActivity.class);
startActivity(intent);
} else if ("gotoMyRestMoney".equals(str)) {
Intent intent = new Intent(mActivity, MyRestActivity.class);
startActivity(intent);
}
}
}
You need to define the launch mode. There are at least two ways of solving this by either using the manifest file (hint: singleTop) or by using Intent flags (hint: FLAG_ACTIVITY_SINGLE_TOP).
Good luck!
Simpliest approach would be disable control that starts your Activity (button for example) after 1 click, and enable it later with some condition or action. Try it.
You can use this approach.......
((Button)findViewById(R.id.someButton)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button)findViewById(R.id.someButton)).setEnabled(false);
}
});
Happy coding
I am using Vuforia AR sdk and want to create a button on the camera preview on the screen.
I cannot figure out where and how to add the button.
I have edit the camera_overlay_udt.xml like this.. In my layout design i have placed back button and listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/camera_overlay_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/headerLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#drawable/header"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#android:color/transparent"
android:src="#drawable/back" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Swipart"
android:textColor="#color/white"
android:textSize="18dp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/arcstarButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_marginRight="10dp"
android:background="#android:color/transparent"
android:src="#drawable/star_button" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/favListingLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/headerLayout"
android:gravity="top"
android:orientation="horizontal"
android:visibility="visible" >
<ListView
android:id="#+id/favlist"
android:layout_width="120dp"
android:layout_height="match_parent"
android:layout_marginBottom="50dp"
android:layout_marginLeft="7dp"
android:cacheColorHint="#00000000" />
</LinearLayout>
<LinearLayout
android:id="#+id/bottom_bar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:background="#color/overlay_bottom_bar_background"
android:gravity="center_vertical"
android:orientation="horizontal"
android:visibility="visible"
android:weightSum="1" >
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/overlay_bottom_bar_separators" />
<ImageButton
android:id="#+id/camera_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#null"
android:contentDescription="#string/content_desc_camera_button"
android:onClick="onCameraClick"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:src="#drawable/camera_button_background" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_above="#id/bottom_bar"
android:background="#color/overlay_bottom_bar_separators" />
</RelativeLayout>
after that please Edit that ImageTargets.java class
private void addOverlayView(boolean initLayout) {
// Inflates the Overlay Layout to be displayed above the Camera View
LayoutInflater inflater = LayoutInflater.from(this);
mUILayouts = (RelativeLayout) inflater.inflate(
R.layout.camera_overlay_udt, null, false);
mUILayouts.setVisibility(View.VISIBLE);
// If this is the first time that the application runs then the
// uiLayout background is set to BLACK color, will be set to
// transparent once the SDK is initialized and camera ready to draw
if (initLayout) {
mUILayouts.setBackgroundColor(Color.TRANSPARENT);
}
// Adds the inflated layout to the view
addContentView(mUILayouts, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
// Gets a reference to the bottom navigation bar
mBottomBar = mUILayouts.findViewById(R.id.bottom_bar);
// Gets a reference to the Camera button
mCameraButton = mUILayouts.findViewById(R.id.camera_button);
mCameraButton.setVisibility(View.GONE);
favButton = (ImageButton) mUILayouts.findViewById(R.id.arcstarButton);
listview = (ListView) mUILayouts.findViewById(R.id.favlist);
backButton = (ImageButton) mUILayouts.findViewById(R.id.backButton);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
finish();
}
});
listview.setVisibility(View.GONE);
galleryList = SendFile.getFavourites();
if (galleryList != null) {
gridviewAdapter = new GridviewAdapter(ImageTargets.this);
listview.setAdapter(gridviewAdapter);
}
favButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (galleryList != null && galleryList.size() > 0) {
if (listview.getVisibility() == View.GONE) {
listview.setVisibility(View.VISIBLE);
} else {
listview.setVisibility(View.GONE);
}
} else {
Toast.makeText(ImageTargets.this, "Favourites not fond",
Toast.LENGTH_LONG).show();
}
}
});
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paramAdapterView,
View paramView, int positon, long paramLong) {
SendFile.setFavourite(galleryList.get(positon));
Intent intent = new Intent(ImageTargets.this,
LoadingScreen.class);
Bundle bundle = new Bundle();
bundle.putInt("x", x_Axis);
bundle.putInt("y", y_Axis);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
});
showDialogHandler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Server Response: " + aResponse, Toast.LENGTH_SHORT)
.show();
showAlertDialog(aResponse);
} else {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Not Got Response From Server.", Toast.LENGTH_SHORT)
.show();
}
};
};
loadingDialogHandler.captureButtonContainer = mUILayouts
.findViewById(R.id.camera_button);
mUILayouts.bringToFront();
}
They showing there layouts using handlers
Start you camera preview in a normal way. Place a layout on top of it with transparent background like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#ff000000"
android:layout_height="match_parent">
<ImageView
android:id="#+id/start_image_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:scaleType="fitXY"
android:layout_weight="1"
android:src="#drawable/scan_image"/>
</RelativeLayout>
In java file, you can add this layout like this:
private View mStartupView;
mStartupView = getLayoutInflater().inflate(
R.layout.startup_screen, null);
// Add it to the content view:
addContentView(mStartupView, new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
This way you will get to see your button on top of camera preview. Hope it helps
You can add buttons in cameraoverlay layout which is in layout folder and you can initialize buttons in initAR function which is in mainactivity.
Step 1: Add the button in the camera_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/camera_overlay_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ProgressBar
style="#android:style/Widget.ProgressBar"
android:id="#+id/loading_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="51dp"
android:text="Button" />
</RelativeLayout>
Step 2: Edit the ImageTargets.java class
private static final String LOGTAG = "ImageTargets";
private Button b1;
Step 3: Modify the initApplicationAR() function of ImageTargets.java class
private void initApplicationAR()
{
// Create OpenGL ES view:
int depthSize = 16;
int stencilSize = 0;
boolean translucent = Vuforia.requiresAlpha();
mGlView = new SampleApplicationGLView(this);
mGlView.init(translucent, depthSize, stencilSize);
mRenderer = new ImageTargetRenderer(this, vuforiaAppSession);
mRenderer.setTextures(mTextures);
mGlView.setRenderer(mRenderer);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
b1.setVisibility(View.GONE);
}
});
}
Now lay back and watch your button disappear on a click!
Although it's a long time since the post.. yet I found one article.. wherein you can have the desired thing..
Ref: https://medium.com/nosort/adding-views-on-top-of-unityplayer-in-unityplayeractivity-e76240799c82
Solution:
Step1: Make a custom layout XML file (vuforia_widget_screen.xml). For example, button has been added.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout">
<FrameLayout
android:id="#+id/unity_player_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#null"
android:text="#string/welcome" />
</FrameLayout>
Step 2: Make following changes in the UnityPlayerActivity.java
Replace "setContentView(mUnityPlayer);" with
setContentView(R.layout.vuforia_widget_screen);
FrameLayout frameLayout = findViewById(R.id.unity_player_layout);
frameLayout.addView(mUnityPlayer.getView());
-> For anyone, who will face the issue in future. :)