Set Click to two different triangular images in a single layout - android

I tried to set click to the triangular images placed as shown in figure. But the problem is only one image click is working. And I have implemented as follows:
<ImageView
android:id="#+id/twoWheeler" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/front_screen_design_twowheeler"
android:scaleType="fitStart"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fourWheeler"
android:src="#drawable/front_screen_design_fourwheeler"
android:scaleType="fitEnd" />
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,BikeActivity.class);
startActivity(i);
}
});
four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,FourActivity.class);
startActivity(i);
}
});

As you have mentioned in your question I have created the same example for your solution.
I have used two images with half transparent area.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rlParent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/triangle" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/triangle2" />
</RelativeLayout>
MainActivity.java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imageView, imageView1;
private RelativeLayout rlParent;
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
rlParent = (RelativeLayout) findViewById(R.id.rlParent);
imageView = (ImageView) findViewById(R.id.imageView);
imageView1 = (ImageView) findViewById(R.id.imageView1);
rlParent.setOnTouchListener(new MyTouchListener(rlParent, this));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageView:
showToast("Image 1 Click");
break;
case R.id.imageView1:
showToast("Image 2 Click");
break;
}
}
private class MyTouchListener implements View.OnTouchListener {
private ViewGroup viewGroup;
private View.OnClickListener onClickListener;
public MyTouchListener(ViewGroup viewGroup, View.OnClickListener onClickListener) {
this.viewGroup = viewGroup;
this.onClickListener = onClickListener;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
for (int pos = 0; pos < viewGroup.getChildCount(); pos++) {
View view = viewGroup.getChildAt(pos);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
int x = (int) event.getX();
int y = (int) event.getY();
if (bitmap.getPixel(x, y) != Color.TRANSPARENT) {
if (onClickListener != null) {
onClickListener.onClick(view);
break;
}
}
}
break;
}
return true;
}
}
}
You can check below screenshots to check particular image click,
Screenshots
I hope it helps you.

The thing with imageview is it takes a rectangular space. So in your case one imageview is placed above another thus only one imageview is clicked. to achieve that you need to create custom class to implement triangular imageview click try this or look for custom imageview...

You can wrap them in a FrameLayout
framelayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//calculate the position by event.getX(),event.getY();
if(point in triOne){
}else{
}
return true;
}
});

Related

How to change setText when i delete the data

I want to change my Button text when i delete the items
i already checked it getText, when i getText it shows that the data
already changed but when i try to setText, it's not show to me
In this case what shold i do?
This is my f_productAdapter
package com.example.together.Adapter;
import android.content.Context;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.example.together.Activities.EditProfileActivity.TAG;
public class f_productAdapter extends BaseAdapter {
Button b;
LayoutInflater inflater = null;
private ArrayList<FuneralProdcutOrder> list;
public f_productAdapter(ArrayList<FuneralProdcutOrder> f_order) {
super();
list = f_order;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return list.get(position).hashCode();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_funeralorder, parent, false);
}
TextView tv_name = convertView.findViewById(R.id.productnm); //상품이름
TextView tv_price = convertView.findViewById(R.id.productpri); //상품 가격
ImageView tv_img = convertView.findViewById(R.id.pro_img);
Button tv_delete = convertView.findViewById(R.id.deleteBtn);
FuneralProdcutOrder getProlist = list.get(position);
tv_name.setText(getProlist.getName());
tv_price.setText(getProlist.getPrice());
Picasso.get().load(getProlist.getImg()).fit().into(tv_img);
LayoutInflater inflaters = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View Toplayout = inflaters.inflate(R.layout.activity_goodbyepet_reservation_result, null );
//
b = Toplayout.findViewById(R.id.f_orderBtn);
TextView test = Toplayout.findViewById(R.id.toolbar_title);
Log.e("test",test.getText()+"");
// Log.e("view context", parent.getContext()+"");
// Log.e("view position", position+"");
// Log.e("view count", list.size()+"");
// Log.e("view",b.getText()+"");
// b.setText("테스트");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("view alert" ,"확실히 버튼 객체를 찾았습니다 눌림");
}
});
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
return convertView;
}
}
This is my reservationResultActivity
package com.example.together.Activities.GoodbyePet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import com.example.together.Adapter.f_productAdapter;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class GoodbyepetReservationResultActivity extends AppCompatActivity {
// private TextView tvParent, tvChild;
Toolbar myToolbar;
ListView funeralview;
Button Btn;
private ArrayList<FuneralProdcutOrder> f_order = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goodbyepet_reservation_result);
int total_price = 0;
//리스트뷰선언
funeralview = findViewById(R.id.funeral_order);
//예약 버튼
Btn = findViewById(R.id.f_orderBtn);
//툴바 선언
myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//액션바 왼쪽에 버튼
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_btn_back);
getSupportActionBar().setDisplayShowTitleEnabled(false);
for (int i = 0; i < MyCategoriesExpandableListAdapter.parentItems.size(); i++ ) {
for (int j = 0; j < MyCategoriesExpandableListAdapter.childItems.get(i).size(); j++ ){
String isChildChecked = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.IS_CHECKED);
if (isChildChecked.equalsIgnoreCase(ConstantManager.CHECK_BOX_CHECKED_TRUE)) {
// tvParent.setText(tvParent.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME));
// tvChild.setText(tvChild.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE));
String name = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME);
String price = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE);
String img = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_IMAGE);
f_order.add(new FuneralProdcutOrder(name,price,img));
total_price = total_price + Integer.parseInt(price);
}
}
}
f_productAdapter orAdapter = new f_productAdapter(f_order);
// orAdapter.setHasStableId(true);
Log.e("view activiey", f_order.size()+"안녕");
funeralview.setAdapter(orAdapter);
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//액션바 등록
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alldelete_manu, menu) ;
return true ;
}
//액션바 클릭 이벤트
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// ((TextView)findViewById(R.id.textView)).setText("SEARCH") ;
return true;
case R.id.settings:
// ((TextView)findViewById(R.id.textView)).setText("ACCOUNT") ;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
What i want to do
when i delete the button directly change buttons text also change
but setText() is not working
how to change that?
Click delete button
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
What i want to change the button text
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
This is my XML That include button what i want to change the text
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".Activities.GoodbyePet.GoodbyepetReservationResultActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/mdtp_white"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예약 상세서"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
/>
</android.support.v7.widget.Toolbar>
<ListView
android:id="#+id/funeral_order"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:drawSelectorOnTop="false">
</ListView>
<Button
android:id="#+id/f_orderBtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:layout_margin="10dp"
android:text="바뀌어주세요"
android:background="#drawable/button_radius"
android:textSize="18dp"/>
</LinearLayout>
Create an interface class like this;
You can set many kind of information as a parameter about your deleted item and send it to your activity.
public interface ItemSelectedListener{
void onItemSelected(boolean isDeleted);
}
In your adapter initialize your interface;
private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();
Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListener listener) {
mItemSelectedSubscribers .add(listener);
}
Set this loop in your click events;
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (ItemSelectedListener listener : mItemSelectedSubscribers ) {
listener.onItemSelected(true);
}
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
In your activity, implement your interface and you will set a implemented methods. this methods look like this;
boolean isDeleted;
#Override
public void onItemSelected(boolean isDeleted) {
this.isDeleted = isDeleted;
}
You know now item is deleted or not. When a button deleted you can change text by using your method.
if(isDeleted){
btn.setText(changeText)
}
Hope this help!

How to make touch events through accessibilty service overlay?

I am currently working on an accessibility service, which has two views. A button and a simple colored view. The colored view appears/disappears when i touch the button.
This is the code for the service -
package com.hardik.accessibiltyservicetest;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.FingerprintGestureController;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import in.championswimmer.sfg.lib.SimpleFingerGestures;
public class Service extends AccessibilityService {
FrameLayout mLayout;
WindowManager.LayoutParams lp;
LayoutInflater inflater;
WindowManager wm;
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
// Create an overlay and display the action bar
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
mLayout = new FrameLayout(this);
lp = new WindowManager.LayoutParams();
lp.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
lp.format = PixelFormat.TRANSLUCENT;
lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
lp.gravity = Gravity.CENTER;
inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.action_bar, mLayout);
wm.addView(mLayout, lp);
configurePowerButton();
}
boolean is = true;
private void configurePowerButton() {
SimpleFingerGestures obj = new SimpleFingerGestures();
obj.setDebug(true);
obj.setConsumeTouchEvents(true);
obj.setOnFingerGestureListener(new SimpleFingerGestures.OnFingerGestureListener() {
#Override
public boolean onSwipeUp(int i, long l, double v) {
Log.e("Swipe", "Up "+i);
return false;
}
#Override
public boolean onSwipeDown(int i, long l, double v) {
return false;
}
#Override
public boolean onSwipeLeft(int i, long l, double v) {
return false;
}
#Override
public boolean onSwipeRight(int i, long l, double v) {
return false;
}
#Override
public boolean onPinch(int i, long l, double v) {
return false;
}
#Override
public boolean onUnpinch(int i, long l, double v) {
return false;
}
#Override
public boolean onDoubleTap(int i) {
return false;
}
});
Button powerButton = mLayout.findViewById(R.id.power);
final View img = mLayout.findViewById(R.id.view);
powerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//performGlobalAction(GLOBAL_ACTION_POWER_DIALOG);
Toast.makeText(getApplicationContext(), "yus", Toast.LENGTH_SHORT).show();
if (is){
is = false;
img.setVisibility(View.GONE);
}
else{
is =true;
img.setVisibility(View.VISIBLE);
}
}
});
img.setOnTouchListener(obj);
}
}
and this is the layout file -
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/power"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:background="#80FFFFFF"
android:text="Test"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/view"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#000000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
the touch event and all works fine. but the problem is that with the current windowmanager parameter length and breadth set to match parent, the overlay blocks touch events to android ui itself, in other words no part of the android ui will respond unless the overlay is stopped, since the overlay consumes all the touch input. And the biggest setback is that i want the overlay to be just like i designed in the layout, and by setting any other length and breadth parameter the background touch problem starts, that is it once again starts consuming the touch events.
It isn't consuming all the touch events when i set the parameters to wrap content, but that doesn't give me the required ui of the service.
Also don't mind the use of gesture library, the code is a part of my personal project.
thanks in advance.
i found a fix. just make separate layouts for each element

How to create a custom drag shadow?

What I want to achieve:
I want to create a drag and drop functionality in Android. I'd like to use a specific layout (different from the dragged object itself) as a drag shadow.
What result I'm getting instead:
Neither of my approaches works as expected - I end up with no visible drag shadow at all (although the target does receive the drop).
What I tried:
I tried
inflating the drag_item layout in the activity, then passing it as an argument to the shadow builder's constructor
and
inflating the drag_item layout in the shadow builder's onDrawShadow method, then drawing it on the canvas
Layouts:
My activity layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app.DragDropTestActivity"
tools:ignore="MergeRootFrame">
<TextView
android:id="#+id/tvReceiver"
android:text="Drop here"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnDragged"
android:layout_height="wrap_content"
android:text="Drag me"
android:layout_width="match_parent"/>
</LinearLayout>
The layout I want to use as a drag shadow:
dragged_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dragged Item"/>
</LinearLayout>
Source code:
Here's the code with both approaches (represented by 1, BuilderOne and 2, BuilderTwo, respectively):
package com.example.app;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class DragDropTestActivity extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag_drop_test);
Button dragged = (Button) findViewById(R.id.btnDragged);
dragged.setOnTouchListener(
new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() != MotionEvent.ACTION_DOWN) {
return false;
}
LayoutInflater inflater = getLayoutInflater();
int approach = 1;
// both approaches fail
switch (approach) {
case 1: {
View draggedItem = inflater.inflate(R.layout.dragged_item, null);
BuilderOne builder = new BuilderOne(draggedItem);
v.startDrag(null, builder, null, 0);
break;
}
case 2: {
BuilderTwo builder = new BuilderTwo(inflater, v);
v.startDrag(null, builder, null, 0);
break;
}
}
return true;
}
});
}
My BuilderOne class:
public static class BuilderOne extends View.DragShadowBuilder
{
public BuilderOne(View view)
{
super(view);
}
#Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint)
{
super.onProvideShadowMetrics(
shadowSize,
shadowTouchPoint);
}
}
And BuilderTwo class:
public static class BuilderTwo extends View.DragShadowBuilder
{
final LayoutInflater inflater;
public BuilderTwo(LayoutInflater inflater, View view)
{
super(view);
this.inflater = inflater;
}
#Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint)
{
super.onProvideShadowMetrics(
shadowSize,
shadowTouchPoint);
}
#Override
public void onDrawShadow(Canvas canvas)
{
final View draggedItem = inflater.inflate(R.layout.dragged_item, null);
if (draggedItem != null) {
draggedItem.draw(canvas);
}
}
}
}
Question:
What do I do wrong?
Update:
Bounty added.
Kurty is correct in that you shouldn't need to subclass DragShadowBuilder in this case. My thought is that the view you're passing to the DragShadowBuilder doesn't actually exist in the layout, and therefore it doesn't render.
Rather than passing null as the second argument to inflater.inflate, try actually adding the inflated View to the hierarchy somewhere, and then passing it to a regular DragShadowBuilder:
View dragView = findViewById(R.id.dragged_item);
mDragShadowBuilder = new DragShadowBuilder(dragView);
v.startDrag(null, mDragShadowBuilder, null, 0);
EDIT
I'm aware that having the dragged_item view being rendered all the time isn't what you want, but if it works then at least we know where the problem is and can look for a solution to that instead!
Simply put it, you only need this:
private final class TouchListener implements View.OnTouchListener {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
v.startDrag(ClipData.newPlainText("", ""), new View.DragShadowBuilder(v), v, 0);
}
return true;
}
}
(You don't necessarily need the BuilderOne and BuilderTwo class)

ontouch and onclick on a textview not working

have a look at the code below...
i am setting the onclick listener on the textview and the ontouch listener but none of them is working...
what seems to be the problem>....?
AlertDialog.Builder builder;
AlertDialog a;
TextView text,txtNewUser ;
ImageView image;
View layout;
Button ok;
String pswrd;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
final Context mContext = this;
Dialog dialog = new Dialog(mContext);
inflater = (LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
ok = (Button) findViewById(R.id.buttonOK);
dialog.setContentView(R.layout.custom_dialog_private_space);
dialog.setTitle("Password");
dialog.setCancelable(true);
layout = inflater.inflate(R.layout.custom_dialog_private_space,
(ViewGroup) findViewById(R.id.layout));
text = (TextView) dialog.findViewById(R.id.tvDesc);
txtNewUser = (TextView) dialog.findViewById(R.id.tvNewUser);
image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.lock_symbol_android);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
a = builder.create();
a.show();
txtNewUser.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_UP)
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
Log.v("AS", "Clicked");
return true;
}
});
txtNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
Log.v("AS", "Clicked");
}
});
}
here is the code of textview from the xml of the dialog layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/layout" >
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvNewUser"
android:text="New User?"
android:layout_gravity="top|left"
android:clickable="true"
/>
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/tvDesc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Enter password"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="100"
android:inputType="textPassword" >
</EditText>
<Button
android:id="#+id/buttonOK"
android:layout_width="100dp"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:text="OK" />
</LinearLayout>
Instead of infalter use window class
return false in on Touch listener
set contenet view to your main activity
package com.collabera.labs.sai;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class HomePage extends Activity {
AlertDialog.Builder builder;
AlertDialog a;
TextView text, txtNewUser;
ImageView image;
Button ok;
String pswrd;
public Window mWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog_private_space);
ok = (Button) findViewById(R.id.buttonOK);
final Context mContext = this;
Dialog dialog = new Dialog(HomePage.this);
dialog.setContentView(R.layout.custom_dialog_private_space);
dialog.setTitle("Password");
dialog.setCancelable(true);
dialog.show();
mWindow = dialog.getWindow();
Log.w(" dialog is " + mWindow.toString(), "-------");
text = (TextView) mWindow.findViewById(R.id.tvDesc);
txtNewUser = (TextView) mWindow.findViewById(R.id.tvNewUser);
image = (ImageView) mWindow.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
txtNewUser.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP)
Toast.makeText(mContext, "Touched", Toast.LENGTH_SHORT)
.show();
Log.v("AS", "Touched");
return false;
}
});
txtNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
Log.v("AS", "Clicked");
}
});
}
}
I think.. you should also return
return super.onTouchEvent(event);
from onTouch function.. instead of true because true means the event is consumed by touch and other actions are not called for this event.. in this case onClick
this is the way i used to make imageview clickable:
public class Main extends Activity **implements OnClickListener** {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView profile_btn=(ImageView) findViewById(R.id.x_Btn);
x_btn.setOnClickListener(this) ;
ImageView food_btn=(ImageView) findViewById(R.id.y_Btn);
ybtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.x_Btn:
//do some thing;break;
case R.id.y_Btn:
//do some thing;break;
}
}
}
In toast both cases you have written clicked so change to touch in onTouch listener and return false at onTouch Listener:
public class HomePage extends Activity {
private TextView txtNewUser;
private Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = getApplicationContext();
txtNewUser = (TextView) findViewById(R.id.tvNewUser);
txtNewUser.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_UP)
Toast.makeText(mContext, "Touched ", Toast.LENGTH_SHORT)
.show();
Log.v("AS", "Touched");
return false;
}
});
txtNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
Log.v("AS", "Clicked");
}
});
}

codes in onClickListener can't be executed

I'm experiencing problem with the following code, I created two buttons with onClickListener added.
It works fine for the Button -- btnAbout, I'm trying to use another way to handle btnIntro, instead of by using findViewById(...) method, but the statement will not be executed when I click btnIntro.
Why does this happen?
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TestActivity extends Activity {
private final String TAG = "tag";
private Button btnIntro;
private Button btnAbout;
private View layoutView;
private ViewWrapper wrapper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAbout = (Button) findViewById(R.id.btnAbout);
if (btnIntro == null) {
LayoutInflater inflator = getLayoutInflater();
layoutView = inflator.inflate(R.layout.main, null, false);
wrapper = new ViewWrapper(layoutView);
layoutView.setTag(wrapper);
} else {
wrapper = (ViewWrapper) layoutView.getTag();
}
btnIntro = wrapper.getButton();
Log.e(TAG, Integer.toHexString(layoutView.getId()) + "");
Log.e(TAG, btnIntro.getText().toString());
btnIntro.setOnClickListener(new OnClickListener() {
{
Log.e(TAG, "static");
}
#Override
public void onClick(View arg0) {
Log.e(TAG, "btnIntro clicked");
Toast.makeText(TestActivity.this, "btnIntro", Toast.LENGTH_SHORT)
.show();
}
});
btnAbout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e(TAG, "btnAbout clicked");
Toast.makeText(TestActivity.this, "about", Toast.LENGTH_SHORT).show();
}
});
}
class ViewWrapper {
View base;
Button btn1;
ViewWrapper(View base) {
this.base = base;
}
Button getButton() {
if (btn1 == null) {
btn1 = (Button) base.findViewById(R.id.btnIntro);
Log.e(TAG, btn1.getText().toString());
}
return btn1;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MAIN_LAYOUT_XML"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="30dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Test" />
<Button
android:id="#+id/btnIntro"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btnIntro" />
<Button
android:id="#+id/btnAbout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btnAbout" />
</LinearLayout>
Problem is that you use to different content views to obtain buttons, one is created when you invoke setContentView() and second you create by invoking inflator.infate(). Thus buttons you get are placed in different content views (only one of which is shown - that created by setContentView). Try that instead:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflator = getLayoutInflater();
layoutView = inflator.inflate(R.layout.main, null, false);
setContentView(layoutView);
//..anything you need..
}

Categories

Resources