Creating a button in java file on android - java

I'm making a game and currently I have this java file
package pap.crowslanding;
import android.os.Bundle;
public class Game extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tester1);
}
}
Using my custom layout GameView, I have tried to merge it with my xml file tester1
<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"
android:background="#drawable/cl_bg"
android:gravity="fill_horizontal">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="32dp"
android:layout_marginTop="42dp"
android:text="#string/hello_world" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="31dp"
android:orientation="horizontal" >
<Button
android:id="#+id/play_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/custom_button"
android:text="#string/first_button"
android:textColor="#drawable/text_color_white" />
<Button
android:id="#+id/sbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#drawable/custom_button"
android:text="#string/menu_settings"
android:textColor="#drawable/text_color_white" />
</LinearLayout>
</RelativeLayout>
<pap.crowslanding.GameView
android:id="#+id/GameView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></pap.crowslanding.GameView
>
</RelativeLayout>
Now:
setContentView(R.layout.tester1);
Will not work for some reason but
setContentView(GameView(this));
Works, any help please
Sorry if this seems easy, I'm quite new and still getting my head around it. Thank you for reading.

You could create a layout that contains your GameView and a Button, and use it as your content view.
Create a file main.xml in res/layout like this:
<?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:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Text" />
<pap.crowslanding.GameView
android:id="#+id/game_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
Then, in onCreate in your Activity, tell it to use the layout as the content view. You can then grab a reference to your GameView and the Button, adding click listeners or whatnot.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GameView gameView = (GameView) findViewById(R.id.game_view);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// respond to clicks
}
});
}
Edit:
Make sure your GameView class implements all three constructors from its super:
public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO
}
public GameView(Context context) {
super(context);
// TODO
}

You cannot draw a Button yourself. You need to wrap your custom View into an XML layout and add the Button there. See here for an example. You can do the same programmatically, if you really want to do it in the code, but you still gonna need to wrap it in a layout.

Related

How to call class as an Activity when class has extends LinearLayout

as my title says I'm here with a problem in Android studio (JAVA) with my app, how to call class as an Activity when class has extends LinearLayout?
My class is:
public class CustomCalendar extends LinearLayout {
My code where I try to call it:
Intent customCalendar = new Intent(MainActivity.this, CustomCalendarActivity.class);
startActivity(customCalendar);
I tried to make this:
public class CustomCalendarActivity extends AppCompatActivity {
CustomCalendar customCalendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
customCalendar = (CustomCalendar) findViewById(R.id.kalendoriaus_virsus);
customCalendar.SetUpCalendar();
}
}
My crash is this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.kalendorius.CustomCalendar.SetUpCalendar()' on a null object reference
at com.example.kalendorius.MainActivity$2.onClick(MainActivity.java:75)
75 Line is:
startActivity(customCalendar);
How I setup my calendar:
My kalendorius.xml:
<?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:id="#+id/kalendoriaus_virsus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/soft_blue_green"
android:orientation="horizontal"
android:paddingTop="8dp"
android:paddingBottom="8dp">
<ImageButton
android:id="#+id/atgalBtn"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="10dp"
android:background="#drawable/back" />
<TextView
android:id="#+id/dabartineData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_weight="3"
android:gravity="center"
android:text="Data"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold" />
That's just a bit code where I use that kalendorius_virsus.
DONE. I figure out what was the problem. I just forgot to generate for database constructor:D Thank you for everyone who tried to help.
The problem is
customCalendar = (CustomCalendar) findViewById(R.id.kalendoriaus_virsus);
The groupView LinearLayout with id kalendorias_virsus in the kalendorias.xml is not a CustomCalendar so always return null.
You need to understand how to properly user a costum view
basic example CustomView ->
public class CustomView extends LinearLayout {
public CustomView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
View view = LayoutInflater.from(getContext()).inflate(
R.layout.costum, null);
this.addView(view);
}
public void setCustomText(String text){
TextView textview = (TextView) findViewById(R.id.textViewId);
textview.setText(text);
}
}
layout custom.xml ->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewId"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/app_name"
android:gravity="center">
</TextView>
</LinearLayout>
activity.xml->
<LinearLayout 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="vertical"
tools:context=".MainActivity">
<com.example.myapplication.CustomView
android:id="#+id/customViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity class->
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomView customView = findViewById(R.id.customViewId);
customView.setCustomText("Welcome ");
}
}
You have many errors in your code. We still need more information to determine why you are getting a NullPointerException (NPE) in the MainActivity.onClick() method. However, this will for sure crash:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
customCalendar = (CustomCalendar) findViewById(R.id.kalendoriaus_virsus);
customCalendar.SetUpCalendar();
}
because customCalendar will be null because you have not called setContentView() before calling findBiewById().
You need to add
setContentView(R.layout.XXXXXX);
before you call findViewById(). The XXXXXX above must be the name of your layout XML file (without the .xml file extension).

Android - Getting a null pointer exception when calling custom View method

I'm new to android and i'm trying to call a method that moves a circle drawn by a custom view using canvas up by 10 pixels. When i try to call said method, i get a null pointer exception and i can't figure out why. Here is what i have.
Main Activity
public class CustomView extends Activity {
XView xv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customview);
}
public void moveUp(View view){
xv.setY(view);
}
}
The Custom View
public class XView extends View implements View.OnClickListener{
private Paint mPaint = new Paint();
int oX = 200;
int oY = 200;
public XView(Context context, AttributeSet attrs){
super(context, attrs);
//setOnClickListener(this);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.MAGENTA);
canvas.drawColor(Color.WHITE);
canvas.drawCircle(oX, oY, 50, mPaint);
}
public void onClick(View view){
oX=oX+10;
view.postInvalidate();
}
public void setY(View view)
{
oY=oY+10;
view.postInvalidate();
}
}
The XML for the main activity
<LinearLayout 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".customview"
android:orientation="vertical">
<com.mycompany.customview.XView
android:layout_width="wrap_content"
android:layout_height="200dp" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/button2"
android:onClick="moveUp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_alignTop="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button"
android:layout_centerHorizontal="true"
android:id="#+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/button5"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/button2" />
</RelativeLayout>
Thanks
you need to add an id to your custom view in your xml:
<com.mycompany.customview.XView
android:id="#+id/xvview_id"
android:layout_width="wrap_content"
android:layout_height="200dp" />
and use findViewById to initialize your member
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customview);
xv = (XView) findViewById(R.id.xvview_id);
}
When you call setContentView, Android "adds", the widgets that you declared in your layout as part of the Activity's view hierarchy, making them available for you in the context of the current activity. What you have to do is just call findViewById to grab a reference to the widget you want to work with

Android Set Custom Preference Layout

I'm working on it Android project. I have a prefs.xml code, something like this
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="pref_name_color_picker"
android:title="Colour"
android:summary="Colour of the name"
android:defaultValue="#FFFFFF"
android:layout="#layout/custom_name_setting_layout" />
</PreferenceCategory>
</PreferenceScreen>
And I need to custom preference layout. And I created;
custom_name_setting_layout.xml
<?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="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingRight="?android:attr/scrollbarSize">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dip"
android:layout_marginRight="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:layout_weight="1">
<TextView
android:id="#+android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal" />
<TextView
android:id="#+android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#android:id/title"
android:layout_alignLeft="#android:id/title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:maxLines="2" />
<ImageView
android:id="#+id/ivNameTextColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="32dp"
android:minWidth="32dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
And write a SettingActivity.java
public class SettingActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
int color = 0xffffff00;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.custom_name_setting_layout, null);
ImageView ivNameTextColor = (ImageView) row.findViewById(R.id.ivNameTextColor);
ivNameTextColor.setBackgroundColor(Color.RED);
}
}
My problem is; I write setBackgroundColor method but not working. Not working meanin is, this program is running without error (like NullReferenceException, there is no error). But background color still not changing.
I don't know why. How can i solve this problem?
Thanks
Obviously, if you are hard-coding the color then you can just do it in your XML:
android:background="#android:color/red"
If you want to do it in code then unfortunately it's trickier than it might seem. You can't just set the color of the preference view in onCreate() because the preference views are stored in a list and are created and recycled dynamically as you scroll the list.
You need to set the background color when the view is being created. To do that you'll need to implement a custom preference class and override getView():
public class CustomColorPreference extends Preference
{
int backgroundColor = Color.BLACK;
public CustomColorPreference(Context context) {
super(context);
}
public CustomColorPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setCustomBackgroundColor(int color)
{
backgroundColor = color;
}
#Override
public View getView(View convertView, ViewGroup parent)
{
View v = super.getView(convertView, parent);
// v.setBackgroundColor(backgroundColor); // set background color of whole view
ImageView ivNameTextColor = (ImageView)v.findViewById(R.id.ivNameTextColor);
ivNameTextColor.setBackgroundColor(backgroundColor);
return v;
}
}
Change your XML to use the CustomColorPreference class:
<com.example.yourapp.CustomColorPreference
android:key="pref_name_color_picker"
android:title="Colour"
android:summary="Colour of the name"
android:defaultValue="#FFFFFF"
android:layout="#layout/custom_name_setting_layout" />
Then in your onCreate you can get the CustomColorPreference and set the color on it using the public method setCustomBackgroundColor():
CustomColorPreference picker = (CustomColorPreference)findPreference("pref_name_color_picker");
picker.setCustomBackgroundColor(Color.RED);

Moving buttons with animation and changing their position afterwards

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>

Android Sliding Drawer Open On Create

I want to have a slider that is open when the app starts. It will be open with buttons and such and when the user closes it, there will be more buttons to access. Is this possible with a sliding drawer? What would I add to the onCreate() method?
Thanks
XML Layout - In a basic LinearLayout:
<SlidingDrawer
android:id="#+id/slide"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:content="#+id/content"
android:handle="#+id/handle"
android:orientation="vertical"
android:scrollbars="vertical" >
<LinearLayout
android:id="#id/handle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/btn"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="#+id/handleImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_tray_expand" />
<Button
android:id="#+id/handleButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#drawable/btn"
android:text="Up me" />
</LinearLayout>
<LinearLayout
android:id="#+id/content"
android:paddingTop="2dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#013E53"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_commentDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="10dp"
android:textSize="20dp" />
</LinearLayout>
</SlidingDrawer>
And your Activity will looks like this:
public class Home extends Activity implements OnDrawerScrollListener
{
private ImageView handleImage;
private Button handleButton;
private SlidingDrawer slide;
private TextView tv_commentDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
tv_commentDisplay = (TextView)this.findViewById(R.id.tv_commentDisplay);
handleImage = (ImageView)this.findViewById(R.id.handleImage);
handleButton = (Button)this.findViewById(R.id.handleButton);
slide = (SlidingDrawer)this.findViewById(R.id.slide);
slide.open(); // not sure
slide.setOnDrawerScrollListener(this);
handleButton = ((Button)this.findViewById(R.id.handleButton));
tv_commentDisplay.setText("Hello World");
}
#Override
public void onScrollEnded() {
}
#Override
public void onScrollStarted() {
if (slide.isOpened())
handleImage.setImageResource(R.drawable.ic_tray_collapse);
else {
handleImage.setImageResource(R.drawable.ic_tray_expand);
}
}
Use open() in your onCreate(), it will open the drawer immediately.
You can take a look at the full API here

Categories

Resources