Moving buttons with animation and changing their position afterwards - java

I am learning Java and Android SDK. I want to create a simple application that is swapping 2 buttons so the left one is moving to the place of right one and v.v. with simple animation. I have tried the ObjectAnimator because I have read that it is moving the views objects permanently. But it's not :-( The objects stays there I mean the left one on the right and v.v. but their getLeft(), getTop() values are the same, and after next animations starts the objects are returning to the start position immediately. I have read that the ObjectAnimator needs some additional function to work properly but in the documentation there is no example :-( I have tried to add the setTranslationX function but it hasn't worked. Could somebody provide me with some simple example of how to do this?
http://developer.android.com/guide/topics/graphics/prop-animation.html#object-animator
"The object property that you are animating must have a setter function (in camel case) in the form of set(). Because the ObjectAnimator automatically updates the property during animation, it must be able to access the property with this setter method. For example, if the property name is foo, you need to have a setFoo() method. If this setter method does not exist, you have three options:
Add the setter method to the class if you have the rights to do so.
Use a wrapper class that you have rights to change and have that wrapper receive the value with a valid setter method and forward it to the original object.
Use ValueAnimator instead."
Thanks in advance.

try this code:
public class ActivityStartup extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("hello");
setContentView(R.layout.main);
SlidingMenu menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.SLIDING_WINDOW);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setBehindOffset(100);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
View view = G.layoutInflater.inflate(R.layout.menu, null);
view.findViewById(R.id.layout_crop).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(G.context, "Crop Clicked", Toast.LENGTH_SHORT).show();
}
});
view.findViewById(R.id.img_logo).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://example.com"));
startActivity(browserIntent);
}
});
menu.setMenu(view);
}
}
public class G extends Application {
public static LayoutInflater layoutInflater;
public static Context context;
#Override
public void onCreate() {
super.onCreate();
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
context = getApplicationContext();
}
}
main.xml is:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
menu.xml is:
<ImageView
android:id="#+id/img_logo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#drawable/hlogo" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:background="#00ff00"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:id="#+id/layout_crop"
android:layout_width="match_parent"
android:layout_height="48dip"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#android:drawable/ic_menu_crop" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Crop"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_day"
android:layout_width="match_parent"
android:layout_height="48dip"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/ImageView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#android:drawable/ic_menu_day" />
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Day"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_delete"
android:layout_width="match_parent"
android:layout_height="48dip"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/ImageView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dip"
android:scaleType="centerInside"
android:src="#android:drawable/ic_menu_delete" />
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:textColor="#000000" />
</LinearLayout>

Related

setBackgroundColor is crashing the android application

I recently made a small app that should change the background color & text of the application when a certain amount of money is generated (here 100000). However, whenever I go past 10000, the application crashes. I am not sure why and can not get around it. I saw that this problem is with background color only because it is otherwise displaying text correctly.
Here is the XML for activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/Trial"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EC5353"
tools:context=".MainActivity">
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="92dp"
android:gravity="center"
android:text="#string/Title"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/money"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="72dp"
android:text="#string/moneyPresent"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Title" />
<Button
android:id="#+id/moneyGenerator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="72dp"
android:background="#FFFFFF"
android:backgroundTint="#732424"
android:backgroundTintMode="multiply"
android:text="#string/generateMoneyButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/money" />
<TextView
android:id="#+id/richTag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="#string/grind_boi"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/moneyGenerator" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my Java Code (Omitted the packages as it would take a lot of space. Do tell me if anyone wants to read it.)
public class MainActivity extends AppCompatActivity {
private Button makeMoney;
private int totalMoney=0;
private TextView moneyText;
private TextView richAlert;
private ConstraintLayout background;
NumberFormat currency=NumberFormat.getCurrencyInstance(new Locale("en","in"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeMoney = findViewById(R.id.moneyGenerator);
moneyText=findViewById(R.id.money);
richAlert=findViewById(R.id.richTag);
makeMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
totalMoney+=1000;
moneyText.setText(currency.format(totalMoney));
Log.d("MoneyTag", "Money Made: "+totalMoney);
Toast.makeText(getApplicationContext(),"Total Money= \u20B9"+totalMoney,Toast.LENGTH_LONG)
.show();
if(totalMoney>=10000) {
richAlert.setText("Welcome to moneyland bro ๐Ÿ˜");
background.setBackgroundColor(16776960);
}
}
});
}
}
makeMoney = findViewById(R.id.moneyGenerator);
moneyText=findViewById(R.id.money);
richAlert=findViewById(R.id.richTag);
You're finding all the views, except background(ConstraintLayout), that's why it is throwing NullPointerException (Most likely, because you haven't attached logs).
You need to find the layout first
background = findViewById(R.id.Trial);
in onCreate.
you haven't defined "background" view in the above.
to use .setBackgroundColor you need to use it with some view
try making object of layout view then change the color of that layout
mConstraintLayout =
(ConstraintLayout)findViewById(R.id.Trial);
makeMoney = findViewById(R.id.moneyGenerator);
moneyText=findViewById(R.id.money);
richAlert=findViewById(R.id.richTag);
if(totalMoney>=10000) {
richAlert.setText("Welcome to moneyland bro ๐Ÿ˜");
mConstraintLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow));
background = findViewById(R.id.Trial);
just find layout and null pointer excpetion will removed

onClick method not working in android studio

I made a side navigation drawer and it works fine but whenever I click any option in navigation drawer nothing happens.It's like it is not taking any input. Onclicking any option I want to redirect user to a new activity but unfortunately it doesn't happens.
XML code is as follows
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="ClickTournament_info"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tournament Info"
android:padding="12dp"
android:layout_marginStart="16dp"/>
<ImageView
android:layout_marginTop="-10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="48dp"
android:src="#drawable/tournament_info"/>
</LinearLayout>
Java code is as follows
public void ClickTournament_info(View view){
redirectActivity(this,TournamentInfo.class);
}
public static void redirectActivity(Activity activity,Class aClass) {
//Initialize intent
Intent intent = new Intent(activity,aClass);
//set flag
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//start activity
activity.startActivity(intent);
}
I think you need to use the onNavigationItemSelected method when you want to handle click events on the navigation drawer.
Learn more: https://developer.android.com/reference/com/google/android/material/navigation/NavigationView.OnNavigationItemSelectedListener#onNavigationItemSelected(android.view.MenuItem)
Firstly, try to always create an Onclicklistener instead of adding an onclick attribute in xml.
In your xml, add an ID attribute to your linear layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearlayout"
android:orientation="horizontal"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="ClickTournament_info"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Tournament Info"
android:padding="12dp"
android:layout_marginStart="16dp"/>
<ImageView
android:layout_marginTop="-10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="48dp"
android:src="#drawable/tournament_info"/>
</LinearLayout>
Now in your classfile inside the Oncreate Method,
LinearLayout LinearLayout = (LinearLayout )findViewById(R.id.linearlayout);
LinearLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
redirectActivity(this,TournamentInfo.class);
}
});
You already have an onClick method. start navigating from that method only.
Try like this,

Add ImageButton to ListView

Im trying to add an ImageButton to each row in my ListView (which I implemented via CustomAdapter). Each button should open a different WebView. I can't seem to find any tutorials to do this so any advice/tips/links would be highly apreciated.
EDIT 1:
My Listview XML:
<?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"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_x="15dp">
<ImageView
android:layout_width="30dp"
app:srcCompat="#drawable/a"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:id="#+id/local"
android:layout_height="30dp"
android:layout_alignBottom="#+id/versus"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/resultsiz"
android:textColor="#android:color/white"
android:textStyle="normal|bold"
android:gravity="center_vertical"
android:elevation="15dp"
android:layout_alignBaseline="#+id/resultsde"
android:layout_alignBottom="#+id/resultsde"
android:layout_alignRight="#+id/resultsde"
android:layout_alignEnd="#+id/resultsde"
android:layout_marginRight="61dp"
android:layout_marginEnd="61dp" />
<ImageView
android:layout_width="15dp"
app:srcCompat="#drawable/a"
android:id="#+id/versus"
android:layout_height="15dp"
android:layout_marginLeft="31dp"
android:layout_marginStart="31dp"
android:layout_alignBottom="#+id/visit"
android:layout_toRightOf="#+id/local"
android:layout_toEndOf="#+id/local" />
<ImageView
android:layout_width="30dp"
app:srcCompat="#drawable/a"
android:id="#+id/visit"
android:layout_height="30dp"
android:layout_marginLeft="19dp"
android:layout_marginStart="19dp"
android:layout_alignBottom="#+id/resultsiz"
android:layout_toRightOf="#+id/versus"
android:layout_toEndOf="#+id/versus" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/local"
android:layout_alignStart="#+id/local"
android:id="#+id/dia"
android:textColor="#color/white"
android:textStyle="normal|bold"
android:textAllCaps="true" />
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/resultsde"
android:layout_marginRight="24dp"
android:layout_marginEnd="24dp"
android:textColor="#android:color/white"
android:layout_marginTop="19dp"
android:textStyle="normal|bold"
android:textAlignment="viewEnd"
android:gravity="end"
android:layout_width="70dp"
android:layout_below="#+id/dia"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/local"
android:layout_toRightOf="#+id/local"
android:layout_toEndOf="#+id/local"
android:layout_marginTop="155dp"
android:id="#+id/stats" />
</RelativeLayout>
And my CustomAdapter:
protected void onPostExecute(Void aVoid) {
CustomAdapter customAdapter = new CustomAdapter();
lista.setAdapter(customAdapter);
}
class CustomAdapter extends BaseAdapter{
#Override
public int getCount() {
return resultsizq.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = getLayoutInflater().inflate(R.layout.customlayout,null);
ImageView versus = (ImageView)view.findViewById(R.id.versus);
ImageView local = (ImageView)view.findViewById(R.id.local);
ImageView visit = (ImageView)view.findViewById(R.id.visit);
TextView dia= (TextView)view.findViewById(R.id.dia);
TextView resultsiz= (TextView)view.findViewById(R.id.resultsiz);
TextView resultsde= (TextView)view.findViewById(R.id.resultsde);
dia.setText(di[position]);
resultsiz.setText(resultsizq[position]);
resultsde.setText(resultsder[position]);
versus.setImageResource(versu[position]);
local.setImageResource(loc[position]);
visit.setImageResource(vis[position]);
if ((position+1)%4==0){
view.setPadding(0,0,0,150);
}
if ((position)%4==0){
view.setPadding(0,150,0,0);
}
return view;
}}
In the getView method, you should assign the onClick function to the Button according to the given position. Probably, you should get the item located at position, generate some url based on the properties of this item, and let this url be opened in the onClick function.
More than that, I have 3 suggestions to improve your code:
Try to use RecyclerView instead of ListView.
Even if you use ListView, have a look at View Holder pattern. This is a good place to start.
Consider using Butterknife, which increases the readability of your code. If I were you, I would keep the item as a property in the view holder object, which has a function annotated with #OnClick(R.id.stats) so that it opens the preferred WebView accordingly.
I hope these help.

Fragment replacing returns NullPointerException

There are many topics on this subject, but I couldn't find any solution that helped my case.
IDEA BEHIND:
What I have is a ViewPager, for swipping between 3 fragments. That works. But in one of the mentioned fragments, I do some functionalities - which then I check in another one of those before mentioned Fragments. Everything works.
Then, when I do the check, I open an AlertDialog, telling the user that his configuration is succesfull. By button click, I want that app transfers the user to one different Fragment (not one of the ViewPager fragments).
CODE SNIPPET - FragmentTwo:
public void displayAlertSuccess(Context ctx) {
new AlertDialog.Builder(ctx)
.setTitle("ACCESS GRANTED!")
.setMessage("Congratulations!")
.setPositiveButton("Great!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with
replaceFragment();
}
})
.setNegativeButton("Format my Card", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mainActivity.setNFC_ACTION("FORMAT");
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.show();
}
private void replaceFragment() {
Fragment frag = new CardDesfire1();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
}
CODE SNIPPET - XML Layouts:
I. activity_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
II. activity_access.xml
<!-- activity_screen_slide.xml -->
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
III. fragment_access_slide2.xml (fragment that has the Dialog)
<!-- fragment_screen_slide_page.xml -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0080ff">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/imageButton"
android:src="#drawable/img_access_slide2_2"/>
</ScrollView>
IV. activity_desfire1.xml (Fragment that I want to launch onClick)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#drawable/bg_des2">
<Button
android:layout_width="fill_parent"
android:layout_height="25dp"
android:text="You have discovered..."
android:id="#+id/btn_des1_discovered"
android:background="#3A5FCD"
android:typeface="monospace"
android:textColor="#ffffffff"
android:enabled="false"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn_loy"
android:text="Loyalty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttons_shape"
android:shadowColor="#000000"
android:textColor="#FFFFFF"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:layout_above="#+id/btn_pay"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:visibility="invisible"/>
<Button
android:id="#+id/btn_pay"
android:text="ยตPay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttons_shape"
android:shadowColor="#000000"
android:textColor="#FFFFFF"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:textAllCaps="false"
android:layout_alignParentBottom="true"
android:layout_marginBottom="70dp"
android:layout_centerHorizontal="true"
android:visibility="invisible"/>
<Button
android:id="#+id/btn_acc"
android:text="Access"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttons_shape"
android:shadowColor="#000000"
android:textColor="#FFFFFF"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:textAllCaps="false"
android:layout_above="#+id/btn_pay"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="invisible"/>
<ImageView
android:layout_width="wrap_content"
android:visibility="invisible"
android:layout_height="wrap_content"
android:id="#+id/img_card_des1"
android:layout_below="#+id/btn_des1_discovered"
android:src="#drawable/img_card_des1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:visibility="invisible"
android:textSize="18dp"
android:gravity="center"
android:text="#string/des1_desc"
android:id="#+id/tv_des1_desc"
android:textColor="#ffffffff"
android:textStyle="italic"
android:background="#ff8db6cd"
android:layout_below="#+id/img_card_des1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp" />
</RelativeLayout>
LINE OF ERROR:
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
Error Description from LogCat:
java.lang.NullPointerException
Error occurs when:
My error occurs when the user clicks the button "Great" in AlertDialog, which should then invoke the Fragment replacement.
I have tried:
I have tried to fix it with the getChildFragment , but then I get different kind of error: IllegalStateException : Activity has been destroyed.
Any help is kindly appreciated.
Have you declared default constructor in your CardDesfire1 fragment. If not then declare it
public CardDesfire1(){}
Make your parent Activity extend FragmentActivity
class ParentActivity extends FragmentActivity
The problem occurs because you call getFragmentManager() in a Fragment, you should delegate displaying the dialog to the activity.
Make activity implement an interface, and have the fragment call this interface method when it's time to show the dialog.
Example: You define a new inner interface in FragmentTwo(this code goes in FragmentTwo):
public interface OnReplaceFragmentListener {
void onReplaceFragment();
}
You link your activity to the fragment(this code goes in FragmentTwo):
private OnReplaceFragmentListener mCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnReplaceFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnReplaceFragmentListener");
}
}
private void replaceFragment() {
mCallback.onReplaceFragment();
}
Then make activity implement OnReplaceFragmentListener.
And(this code goes into FragmentTwo's hosting activity):
#Override
void onReplaceFragment() {
Fragment frag = new CardDesfire1();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
}

Layering images in Android Studio?

Currently I have a UI designed with imageviews, the problem is they cannot overlap or be layered. (Or if they can, I haven't figure out how)
I'd like to do 3 layers, the bottom layer is the board,
The next layer is pieces,
The next layer is a selected piece with valid moves.
My idea is that I will have listeners on the top layer only.
I am just looking for the best data structure to use for this, the app is a chesslike game I am working on developing.
If there is another approach that might be better I am all ears as well.
Thanks!
As requested code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Game Activity"
android:id="#+id/textView5"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView22"
android:src="#drawable/ni_whitesquare"
android:layout_below="#+id/textView5"
android:layout_alignRight="#+id/textView5"
android:layout_alignEnd="#+id/textView5"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="76dp"
android:contentDescription="whitesquare"
android:clickable="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView32"
android:src="#drawable/ni_blacksquare"
android:layout_alignTop="#+id/imageView22"
android:layout_alignLeft="#+id/imageView22"
android:layout_alignStart="#+id/imageView22"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:contentDescription="blacksquare"
android:clickable="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView12"
android:src="#drawable/ni_blacksquare"
android:contentDescription="blacksquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView22"
android:layout_toLeftOf="#+id/imageView22"
android:layout_toStartOf="#+id/imageView22" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView21"
android:src="#drawable/ni_blacksquare"
android:contentDescription="blacksquare"
android:clickable="true"
android:layout_below="#+id/imageView22"
android:layout_toRightOf="#+id/imageView12"
android:layout_toEndOf="#+id/imageView12" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView23"
android:src="#drawable/ni_blacksquare"
android:contentDescription="blacksquare"
android:clickable="true"
android:layout_above="#+id/imageView12"
android:layout_toLeftOf="#+id/imageView33"
android:layout_toStartOf="#+id/imageView33" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView31"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignBottom="#+id/imageView21"
android:layout_alignLeft="#+id/imageView32"
android:layout_alignStart="#+id/imageView32" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView11"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView21"
android:layout_toLeftOf="#+id/imageView21"
android:layout_toStartOf="#+id/imageView21" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView13"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView23"
android:layout_alignLeft="#+id/imageView12"
android:layout_alignStart="#+id/imageView12" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView33"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView23"
android:layout_alignLeft="#+id/imageView32"
android:layout_alignStart="#+id/imageView32" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/directions"
android:id="#+id/directionsstring"
android:layout_marginTop="30dp"
android:layout_below="#+id/imageView21"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Startingpoint"
android:src="#drawable/ni_pawn"
android:layout_above="#+id/imageView11"
android:layout_toLeftOf="#+id/imageView12"
android:layout_toStartOf="#+id/imageView12" />
</RelativeLayout>
Activity :
public class GameActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final ImageView mStarting = (ImageView) findViewById(R.id.Startingpoint);
final ImageView mCenterSq = (ImageView) findViewById(R.id.imageView22);
final ImageView m12 = (ImageView)findViewById(R.id.imageView12);
mCenterSq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
m12.setImageResource(R.drawable.ni_blacksquare);
mCenterSq.setImageResource(R.drawable.ni_portal);
//center square turns into a portal when clicked.
if (mStarting.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_whitesquare).getConstantState()) &&
mCenterSq.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_portal).getConstantState()) )
{
mCenterSq.setOnClickListener(null);
return;
}
mStarting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//Pawn selected
mStarting.setImageResource(R.drawable.ni_whitesquare);
m12.setImageResource(R.drawable.ni_greensquare);
mCenterSq.setImageResource(R.drawable.ni_greensquare);
if (mStarting.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_whitesquare).getConstantState()))
{
mStarting.setOnClickListener(null);
}
m12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (m12.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_greensquare).getConstantState()))
{
m12.setImageResource(R.drawable.ni_pawn);
mCenterSq.setImageResource(R.drawable.ni_portal);
}
}
});
}
});
};
});
}
}
For layering views, you might want to use a FrameLayout see this answer: Layout Layers? Z-Axis?
Also, if you're trying to set up a layout in which you have several consecutive views that need to be lined up one next to the other, the most appropriate element is usually a LinearLayout. LinearLayout will automatically set up your views in consecutive order in the order you declared them, according to the android:orientation attribute you set for it.
Overall, I'd suggest looking at the docs for each of these. RelativeLayout is probably not the way to go since it involves a lot of managing of view positioning which just seems frivolous for what I think you are trying to do. I hope this helps

Categories

Resources